物件隱式轉換,複製建構函式和過載等號運算子的區別
阿新 • • 發佈:2018-12-29
#include<iostream> #include<string.h> using namespace std; class A{ public: A(char* username) { cnt++; cout << cnt << endl; name = new char[strlen(username)]; strcpy(name,username); cout << username << endl; } A(const A& cp) { /*name = new char[strlen(cp.name)]; strcpy(this->name,cp.name);*/ name = cp.name; cout << cnt << endl; cout << "this name is "<< this->name << "\t" << cp.name << endl; } A& operator= (const A& cp) { name = cp.name; cout << "this name is "<< this->name << "\t" << cp.name << endl; } ~A() { delete name; name = NULL; } private: static int cnt; char* name; }; int A::cnt = 0; int main() { A test1("nihao"); A test2(test1); A test3 = test1; test3 = test2; return 0; }