#include<iostream>
using namespace std;
class A
{
public:
A(int _a)//构造函数 必须使用
{
a = _a;
cout << "a" << a << endl;
}
~A()
{
cout << "构造函数" << "a" << a << endl;
}
protected:
private:
int a;
};
class B
{
public:
B(int _b1, int _b2) :a1(1), a2(2), c(0)//构造函数规划列表
//在b类中组合了一个A类对象(A类设计了构造函数)
//写了A的构造函数 必须要用 没有机会初始化A
{
b1 = _b1;
b2 = _b2;
}
B(int _b1, int _b2, int m, int n) :a1(m), a2(n),c(0)
{
b1 = _b1;
b2 = _b2;
cout << "b的构造函数" << endl;
}
~B()
{
cout << "B的析构函数" << endl;
}
protected:
private:
int b1;
int b2;
A a1;//在一个类里面b组合了带参数的构造函数 没有机会初始化A1 A2
A a2;
const int c;
};
void object10main()
{
A a1(10);
//参数重载 参数传递
//调用顺序
B objB1(1, 2);
B objB2(1, 2,3, 4);
return;
}
//先执行 被组合对象的构造函数
//如果组合对象有多个 按照定义顺序 而不是按照初始化顺序列表
//析构函数:和构造函数的调用顺序相反
//初始化列表 用来给 consr属性赋值
void main()
{
object10main();
return;
}
匿名对象的生命周期只存在于79行 没有东西去接住 构造之后马上析构
给了应一个函数之后 只会调用构造函数 生命周期结束的时候才会调用析构函数
#include<iostream>
using namespace std;
class MyTest
{
public:
MyTest(int a, int b, int c)
{
this->a = a;
this->b = b;
this->c = c;
}
MyTest(int a, int b)
{
this->a = a;
this->b = b;
MyTest(a, b, 100);//在构造函数里面调用构造函数
}
~MyTest()
{
cout << "MyTest" << a << b << c << endl;
}
protected:
private:
int a;
int b;
int c;
public:
int getC()const { return c; }
void setC(int val) { c = val; }
};
void main()
{
MyTest t1(1, 2);
cout << "c" << t1.getC() << endl;
return;
}
定义局部变量t1 .t1 会进栈 - 属性 a b c
执行两个参数的构造函数
直接调用构造函数 产生一个匿名对象
匿名对象没有人接 立马会调用析构函数
匿名对象和t1没有关系