注意:变量名不要和类名一样;构造顺序-先子后母,析构顺序-先母后子。
#include<iostream>
#include<string>
using namespace std;
class phone
{
public:
phone(string num)
{
iphone = num;
cout << "phone的有参构造" << endl;
}
~phone()
{
cout<< "phone析构函数" << endl;
}
//private:
string iphone;
};
class person
{
public:
//下一行中aphone(phone)等价于phone aphone=phone
person(string name, string phone) :aname(name), aphone(phone) //初始化列表
{
cout << "person的有参构造" << endl;
}
~person()
{
cout << "person析构函数" << endl;
}
//private:
string aname;
phone aphone;
};
void test1()
{
person p("bglei", "HUAWEI");
//cout << p.aname << "拿着" << p.aphone.iphone << endl;
}
int main()
{
test1();
system("pause");
return 0;
}
运行结果: