c++拷贝构造函数事例
时间: 2023-11-30 15:42:20 浏览: 84
以下是一个C++拷贝构造函数的例子:
```c++
#include <iostream>
#include <cstring>
using namespace std;
class StringBad {
private:
char *str;
int len;
static int num;
public:
StringBad(const char *s) {
len = strlen(s);
str = new char[len + 1];
strcpy(str, s);
num++;
cout << "调用了构造函数" << endl;
}
StringBad(const StringBad &st) {
str = new char[strlen(st.str) + 1];
strcpy(str, st.str);
len = st.len;
num++;
cout << "调用了拷贝构造函数" << endl;
}
~StringBad() {
cout << "调用了析构函数" << endl;
delete [] str;
num--;
}
StringBad & operator=(const StringBad &st) {
if (this == &st) {
return *this;
}
delete [] str;
str = new char[strlen(st.str) + 1];
strcpy(str, st.str);
len = st.len;
cout << "调用了赋值运算符" << endl; return *this;
}
friend ostream & operator<<(ostream &os, const StringBad &st) {
os << st.str;
return os;
}
};
int StringBad::num = 0;
int main() {
StringBad s1("hello");
StringBad s2(s1);
StringBad s3 = s1;
StringBad s4("world");
s2 = s4;
cout << s1 << endl;
cout << s2 << endl;
cout << s3 << endl;
cout << s4 << endl;
cout << "当前对象数量:" << StringBad::num << endl;
return 0;
}
```
阅读全文