// 类内声明另一个类的对象初始化方法(类的组合初始化方法).cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <string>
using namespace std;
class Cstudent
{
private:
string name;
int StudNumber;
public:
Cstudent(string name, int StudNumber)
{
this->name = name;
this->StudNumber = StudNumber;
}
Cstudent() {};
virtual ~Cstudent()
{
cout << "调用~Cstudent的析构函数" << endl;
}
void ShowInf()
{
cout << this->name << "的学号为" << this->StudNumber << endl;
}
};
class Cperson
{
private:
char sex;
Cstudent stud; // 此处先声明无需定义
public:
Cperson(char sex, Cstudent &stud) // 把类的对象当作普通成员变量初始化
{
this->sex = sex;
this->stud = stud;
}
~Cperson()
{
cout << "调用Cperson的析构函数" << endl;
}
void ShowInf()
{
stud.ShowInf();
cout << "性别为" << this->sex << endl;
}
};
int main()
{
Cstudent stud("大明", 7);
Cperson person('f', stud);
person.ShowInf();
}