构造函数中调用另一个构造函数
#include <iostream>
using namespace std;
class MyTriangle
{
public:
MyTriangle(int a, int b, int c)
{
this->a = a;
this->b = b;
this->c = c;
}
MyTriangle(int a, int b)
{
this->a = a;
this->b = b;
MyTriangle(a, b, 100);//这里的匿名对象产生即会消亡
}
~MyTriangle()
{
cout << "析构函数---a=" << this->a << " ,b=" << this->b << " ,c=" << this->c << endl;
}
protected:
private:
int a;
int b;
int c;
public:
int Get_C_Value() const { return c; }
void Set_C_Value(int val) { c = val; }
};
int main()
{
MyTriangle tri(1, 2);
cout << "c的数据是多少?" << tri.Get_C_Value() << endl;
cin.get();
return 0;
}
结果:c由于没有初始化,所以结果是个垃圾值。
匿名对象中的c内容是100,但这和tri对象没有任何关系,匿名对象会立刻消亡。