您的位置:首页 > 其它

类中嵌套另一个类时,调用构造,析构,拷贝,赋值运算符等函数的次序

2016-06-24 23:32 337 查看
class A
{
public:
A(int a = 0)
:a(a)
{
cout << "A()" << endl;
}
A(const A& other)
{
cout << "A&()" << endl;
}

A& operator =(const A& other)
{
cout << "operator = " << endl;
return *this;
}
~A()
{
cout << "~A()" << endl;
}
private:
int a;
};

class B
{
public:
//B( )  // B* const this 默认参数在此会有this对象会调用类A的构造函数构造自己的
//  //数据成员a
//{
// a = 0; // A()  A()  operator =  ~A  B() ~B()  ~A()  
// // a = 0   ===========  a.operator=(0);  
// // A& operator =(const A& other)函数 
// //在传参时用 0 调用类A的构造函数构造一个临时对象_a(0)给other
// // _a 出了类A的赋值运算符函数会自动调用类A的析构(形参嘛)
// cout << "B()" << endl;
//}

//B() // B* const this 默认参数  在此会有this对象会调用类A的构造函数构造自己的    
// // 数据成员a
// :a(0)   //A()  B()  ~B() ~A()
//{
// cout << "B()" << endl;
//}

B(A d = 0)   // B* const this 默认参数 在此会有this对象会调用类A的构造函数构造自己              
    // 的数据成员a
    //  参数 A d = 0; 会调用类A的构造函数构造对象d
{
a = d; // A()  A()  operator =   B()  ~A   ~B()  ~A() 
    // a = d   ===========  a.operator=(d);  
    // A& operator =(const A& other) 函数
// 在传参时引用传递,不会产生临时对象
// 形参 d 出了类B的构造函数会自动调用类A的析构

//如果A operator =(const A& other) 函数是值返回
//返回时会有一个无名对象产生  
// A()  A()  operator =  A&()  ~A  B() ~A  ~B() ~A() 
cout << "B()" << endl;
}

~B()
{
cout << "~B()" << endl;
}
private:
A a;
};

本文出自 “埋葬的记忆” 博客,请务必保留此出处http://bitersl.blog.51cto.com/10756929/1759929
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: