初始化列表
作用:C++提供了初始化列表语法,用来初始化属性
语法:
构造函数():属性1(值1),属性2(值2).....{ }
传统初始化操作:
#include<iostream>
using namespace std;
class Person
{
public:
//传统初始化操作
Person(int a, int b, int c)
{
m_A = a;
m_B = b;
m_C = c;
}
int m_A;
int m_B;
int m_C;
};
int main()
{
Person a(10, 30, 10);
cout << "a = " << a.m_A << endl;
cout << "b = " << a.m_B << endl;
cout << "c = " << a.m_C << endl;
system("pause");
return 0;
}
初始化列表:
#include<iostream>
using namespace std;
class Person
{
public:
Person(int a,int b,int c) :m_A(a), m_B(b), m_C(c) //初始化列表
{
}
int m_A;
int m_B;
int m_C;
};
int main()
{
Person a(30,20,10);
cout << "a = " << a.m_A << endl;
cout << "b = " << a.m_B << endl;
cout << "c = " << a.m_C << endl;
system("pause");
return 0;
}
类对象作为类成员
C++类中成员可以是另一个类的对象,我们称该成员为成员对象
例如
class A{ };
class B
{
A a;
};
B类中有对象A作为成员,A为对象成员
那么创建B时,A和B的构造函数和析构顺序是谁先谁后呢?
#include<iostream>
#include<string>
using namespace std;
class Phone
{
public:
Phone(string Pname)
{
m_Pname = Pname;
cout << "调用Phone的构造函数" << endl;
}
~Phone()
{
cout << "调用Phone的析构函数" << endl;
}
string m_Pname;
};
class Person
{
public:
Person(string name,string Pname):m_name(name),m_phone(Pname)//隐式转换法
{
cout << "调用Person的构造函数" << endl;
}
~Person()
{
cout << "调用Person的析构函数" << endl;
}
string m_name;
Phone m_phone;
};
int main()
{
Person p("张三", "小米11");
cout << p.m_name << ":" << p.m_phone.m_Pname << endl;
return 0;
}
执行结果如下:
结论:
当其他类的对象作为本类成员,
构造时先构造其他类的对象,在构造自身
析构时先析构自身,再析构其他类对象