class C
{
public:
C(){
name=s;
cout<<name<<"default constructed:"<<endl;
}
C (const C &c){
cout<<name<<": copy constructed using "<<c.name<<endl;
}
~C(){
cout<<name<<" :destructed "<<endl;
}
C& operator=(const C &c){
cout<<name<<" :assigned usingning "<<c.name<<endl;
return *this;
}
private:
string name;
};
主函数
string s="w";
C w;
int main(){
s="x";
C x;
{
s="y";
C y;
}
s="z";
C z(w);
x=w=z;
return 0;
}
输出结果为
w :省略
x:省略
y:省略
y:省略
z: :省略 w
w :省略 z
z :省略 w
z:省略
x:省略
w:省略
C w; // 1 默认构造,此时s 的值为"w"
int main(){
s="x";
C x; // 2 默认构造,此时s 的值为"x"
{
s="y";
C y; // 3 默认构造,此时s 的值为"y"
}// 4 析构,退出被块语句析构里面的局部对象y
s="z";
C z(w); // 5 拷贝构造,用w 构造z
x=w=z;// 6 赋值,z赋值给w
// 7 赋值,w赋值给x
return 0;
}// 8 析构z,结果这一行缺少必要信息,因为构造的z中的字符串为空
// 9 析构x追问
在拷贝构造中输出的name与c.name分别代表什么呢,我一直把 name与s搞混,能解释清楚点吗
追答这是拷贝构造函数的函数体:
C (const C &c){
coutname,为被构造的对象,也就是上面一行的z
c.name就是拷贝构造函数形参的name,也就是w 的name
明白了。其实应该还定义一个name的成员函数吧