定义Person类age,name成员再定义Phone类 子对象,Phone有hm,lx变量,都有构造函数和析构函数C++
时间: 2024-03-04 20:49:39 浏览: 20
下面是定义Person类和Phone类的示例代码:
```c++
#include <iostream>
#include <string>
class Phone {
public:
Phone() : hm(""), lx("") {}
Phone(std::string hm, std::string lx) : hm(hm), lx(lx) {}
~Phone() {}
private:
std::string hm;
std::string lx;
};
class Person {
public:
Person() : age(0), name("") {}
Person(int age, std::string name, Phone phone) : age(age), name(name), phone(phone) {}
~Person() {}
private:
int age;
std::string name;
Phone phone;
};
```
在这个示例中,Phone类是Person类的子对象,即Person类中包含一个Phone对象作为其成员。Phone类中有hm和lx两个变量,分别表示电话号码和类型。在Person类中,我们定义了age和name两个成员变量,以及一个名为phone的Phone对象。在Person类的构造函数中,我们通过参数列表初始化age、name和phone成员变量,其中phone对象也需要通过构造函数初始化。在析构函数中,我们不需要进行任何操作,因为Phone对象会在Person对象被销毁时自动被销毁。