1. 程式人生 > >過載運算子時的引數和返回型別要用引用的說明

過載運算子時的引數和返回型別要用引用的說明

class Myclass {
private:
char* str;
public:
Myclass(char* str1 = "default string") {
str = new char[strlen(str1) + 1];
strcpy(str, str1);
cout << "constructor called" << endl;
}
~Myclass(){
cout << "destrustor called"<<endl;
}
void showChar() {
cout << str << endl;
}
Myclass &operator=(const Myclass &ele) {
delete[] str;
str = new char[strlen(ele.str) + 1];
strcpy(str, ele.str);
return *this;
}
};

int main() {
Myclass class1("string1");
Myclass class2;
class2 = class1;
class1.showChar();
class2.showChar();
return 0;
}