c++构造函数中调用构造函数---匿名对象再探

时间:2023-03-08 16:58:17
c++构造函数中调用构造函数---匿名对象再探
 #include<iostream>
#include<string>
using namespace std;
class Copy_construction {
public:
Copy_construction(int a,int b,int c)
{
this->a = a;
this->b = b;
this->c = c;
cout << "这是Copy_constructiond的有3个默认参数的构造函数! "<<this->a<<" "<<this->b<<" "<<this->c<<endl;
} Copy_construction(int a, int b)
{
this-> a= a;
this->b = b;
Copy_construction(, , );
cout << "这是Copy_constructiond的有2个默认参数的构造函数! " << this->a << " " << this->b << endl;
}
~Copy_construction()
{
cout << "Copy_construction对象被析构了! "<<this->a << " " << this->b << " " << this->c << endl;
} int getC()
{
return c;
}
private:
int a;
int b;
int c; }; int run()
{
Copy_construction aa(, );
cout << aa.getC() << endl; //c的值为垃圾值,因为匿名对象被创建有立即析构了
//就算用不析构的方式,也是垃圾值,因为c是不同对象中的元素
                    //在2个参数的构造函数中,没有显式初始化c,不能通过构造其他对象而在本构造对象中访问未初始化的数据
return ;
}
int main()
{ run();
cout << "hello world!\n";
return ;
}
c++构造函数中调用构造函数---匿名对象再探
如果直接显示调用构造函数,要看怎么去接这个函数, Copy_construction(1,2,3);调用之后马上执行析构匿名对象,
 Copy_construction  T= Copy_construction(1,2,3)此时匿名对象不析构而直接转正成T。
NOTE:
构造函数中调用构造函数是危险的做法。