class People { public: People(int age) { this->age = age; } public: int age; }; int main() { int tempAge = 3; People ZhangSan(tempAge); People LiSi(ZhangSan); return 0; }当执行People LiSi(ZhangSan)时就调用了编译器生成的默认复制构造函数,当执行完这句之后LiSi的age变量就和ZhangSan的age的值得一模一样。
#include<iostream> #include<cstdio> #include<cstring> using namespace std; class Name { public: Name(char* name,int length) { //不能不加this this->name = new char[length]; this->length =length; strcpy(this->name,name); } void printName() { cout<<"The Address of the Name "<<(void*)this->name<<endl; cout<<this->name<<endl; } ~Name() { delete[] this->name; } void setName(char* name,int length) { if(this->length <length) { delete[] name; name = new char[length]; } strcpy(this->name,name); } private: char* name; int length; }; int main() { char* temp="ZhangSan"; Name ZhangSan(temp,strlen(temp)); Name LiSi(ZhangSan); ZhangSan.printName(); LiSi.printName(); temp = "Changed"; ZhangSan.setName(temp,strlen(temp)); ZhangSan.printName(); LiSi.printName(); return 0; }
The Address of the Name 0x611600 ZhangSan The Address of the Name 0x611600 ZhangSan The Address of the Name 0x611600 Changed The Address of the Name 0x611600 Changed
Name(Name& temp) { this->name =temp.name; this->length = temp.length; }
Name(Name& temp) { this->name = new char[temp.length]; this->length = temp.length; if(temp.length!=0) strcpy(this->name,temp.name); }再次运行上次的程序:
The Address of the Name 0x4c1600 ZhangSan The Address of the Name 0x4c1630 ZhangSan The Address of the Name 0x4c1600 Changed The Address of the Name 0x4c1630 ZhangSan从结果可以看出ZhangSan的name和LiSI的name指向不同的地址,在执行了setName()之后LiSi的name并没有受到影响。内存分布如下:
原文:http://blog.csdn.net/csu_stackoverflow/article/details/24286637