C++类的组合
前言
提示:以下是本篇文章正文内容,下面案例可供参考
一、以另一个类的对象为数据成员
1.构造函数的写法
- 构造函数的写法,必须采用初始化参数列表的写法
#include <iostream>
#include <string>
using namespace std;
class Boy
{
public:
Boy(string name, int age) :name(name), age(age){
}
void print()
{
cout << name << "\t" << age << endl;
}
protected:
void printDATA()
{
cout << name << "\t" << age << endl;
}
string name;
int age;
};
class Girl
{
public:
Girl(string boyName, int boyAge, string girlName) :boy(boyName, boyAge) //组合类的构造函数
{
this->girlName = girlName;
}
void print()
{
boy.print();
//boy.printDATA(); 错误 不可访问 boy对于Boy是类外,不可直接访问保护属性
cout << girlName << endl;
}
protected:
string girlName;
Boy boy;
};
int main()
{
Girl nv("nan",