前向引用声明:使编译器提前知道该类名
注意:
使用前向引用声明时,只能使用被声明的符号,而不能涉及类的任何细节
//前向引用声明
class son;
class person
{
};
class son
{
};
在提供一个完整的类定义之前,不能定义该类对象,也不能在内联成员函数中使用该类的对象
class son;
class person
{
son s;//错误:类son定义不完善
};
class son
{
person p;
};
类的嵌套:
class son
{
public:
//构造函数
son();
son(string na, int a, int h) :name(na), age(a), height(h) {cout<<"son的构造函数"<<endl;}
~son(){cout<<"son的析构"<<endl;}
string name;
int age;
int height;
};
class person
{
public:
person(string s, string s1, int a, int h):Name(s),Son(s1,a,h){cout<<"person的构造"<<endl;}
~person(){cout<<"person的析构"<<endl;}
string Name;
son Son;
};
void text()
{
//创建对象
person p("张三","李四",12,150);
cout << "父亲的名字:" << p.Name << endl;
cout << "孩纸的名字:" << p.Son.name << endl;
cout << "孩纸的年龄:" << p.Son.age << endl;
cout << "孩纸的身高:" << p.Son.height << endl;
}
当其他类作为类的对象时,会先构造其他类的对象,然后构造本身对象
构造和析构调用顺序: