RHZ'S BLOG | 个人分享

  • 首页
  • 笔记
  • 小日常
  • 音乐
  • 读书
  • 软件分享
YOLO
  1. 首页
  2. 笔记
  3. C/C++
  4. 正文

组合|C++

2022年9月12日 108点热度 0人点赞 0条评论

组合

在现实世界中,复杂的对象通常是使用更小,更简单的对象来组合的。例如,使用金属框架,发动机,轮胎和大量其他部件来组装汽车。

这个过程被称为组合。

在C++中,对象组合涉及使用类作为其他类中的成员变量。这个示例程序演示了组合。它包含 Person 和 Birthday 类,每个 Person 都有一个生日对象作为其成员。

Birthday:

class Birthday {
 public:
  Birthday(int m, int d, int y)
  : month(m), day(d), year(y)
  { 
  }
 private:
   int month;
   int day;
   int year;
};

我们的生日班有三个成员变量。它还有一个使用成员初始化列表初始化成员的构造函数。

为了简单起见,该类在单个文件中被声明。或者,你也可以使用头文件和源文件。

组合|C++插图
Birthday::Birthday(int m, int d, int y)
:
month(m),
day(d),
year(y
){
}

组合

在我们的 Birthday 类中添加一个 printDate() 函数:

class Birthday {
 public:
  Birthday(int m, int d, int y)
  : month(m), day(d), year(y)
  {
  }
  void printDate()
  {
   cout<<month<<"/"<<day
   <<"/"<<year<<endl;
  }
 private:
  int month;
  int day;
  int year;
};
组合|C++插图1
class People{
public:
private:
int birthDay;
int birthMonth;
int birthYear;
};

接下来,我们可以创建 Person 类,其中包括 Birthday 类。

#include <string>
#include "Birthday.h"

class Person {
 public:
  Person(string n, Birthday b)
  : name(n),
   bd(b)
  {
  }
 private:
  string name;
  Birthday bd;
};

Person 类有一个 name 和一个 Birthday 成员,并有一个构造函数来初始化它们。

注意: 确保包含相应的头文件。

组合|C++插图2
#include<string>
#include"Birthday.h"

class People{
public:
People(string n,Birthday bo);
private:
string name;
Bithday dateOfBirth;
}

现在,我们的 Person 类有一个 Birthday类型的成员:

class Person {
 public:
  Person(string n, Birthday b)
  : name(n),
    bd(b)
  {
  }
 private:
  string name;
  Birthday bd;
};

组合用于共享一个有关系的对象,如 “一个人有一个生日”。

在我们的 Person 类中添加一个 printInfo() 函数,打印对象的数据:

class Person {
 public:
  Person(string n, Birthday b)
  : name(n),
  bd(b)
  {
  }
  void printInfo()
  {
   cout << name << endl;
   bd.printDate();
  }
 private:
  string name;
  Birthday bd;
};

请注意,我们可以调用 bd 成员的 printDate() 函数,因为它的类型是 Birthday,它定义了该函数。

组合|C++插图3
void People::printInfo(){

cout << name << endl;

dateOfBirth.printDate();

}

现在我们已经定义了 Birthday 和 Person 类,我们可以去 main,创建一个 Birthday 对象,然后把它传递给一个 Person 对象。

int main() {
  Birthday bd(9, 13, 2001);
  Person p("RHZ", bd);
  p.printInfo();
}

/*输出
Loen
7/7/1990
*/

我们已经创建了一个日期为 9/13/2001 的生日对象。接下来,我们创建了一个 Person 对象,并将生日对象传递给它的构造函数。

最后,我们使用 Person 对象的 printInfo() 函数打印它的数据。

总的来说,组合可以让每个单独的类相对简单,直接,并专注于执行一项任务。

它还使每个子对象都是独立的,允许重用(我们可以在其他各种类中使用生日类)。

组合|C++插图4
Birthday birthObj(10, 30, 1986);

People yeshu("YeShu", birthObj);
本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可
标签: 暂无
最后更新:2022年9月12日

RHZ

即使单枪匹马,我亦勇敢无畏

点赞
< 上一篇
下一篇 >

文章评论

取消回复
归档
  • 2023年2月
  • 2022年12月
  • 2022年11月
  • 2022年10月
  • 2022年9月
  • 2022年8月
  • 2022年7月
  • 2022年6月
  • 2022年5月
  • 2022年4月
  • 2022年3月
  • 2022年2月
  • 2021年12月
  • 2021年11月
  • 2021年10月
  • 2021年8月
  • 2021年7月

COPYRIGHT © 2022 RHZ的博客. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

渝ICP备2022008933号-1