C++笔记之类的组合详细讲解

本文详细介绍了C++中的类组合概念,包括类组合的定义、原则和声明形式,并通过计算两点间距离、点线三角形的类组合等代码示例进行说明,强调了在构造函数中内嵌对象的初始化顺序以及前向引用的使用注意事项。
摘要由CSDN通过智能技术生成
  • 类的组合
  • 代码示例

一、类的组合

1. 类组合: 类中的成员数据是另一个类的对象或者是另一个类的指针或引用。通过类的组合可以在已有的抽象的基础上实现更复杂的抽象。

2. 原则: 不仅负责对本类中的基本类型成员数据赋初值,也要对内嵌对象成员初始化。

3. 声明形式:
可以是含参构造函数,也可以复制构造函数

类名::类名(形参):内嵌对象1(参数),内嵌对象2(参数)... {
     }

4. 构造函数的调用:

  • 先调用内嵌对象的构造函数(按内嵌时的声明顺序,先声明者先构造),然后再调用本类的构造函数(析构函数的调用顺序相反)
  • 若调用默认构造函数(即没有形参的),则内嵌对象的初始化也将调用相应的默认构造函数。

二、代码示例

例1. 【两点间距离】实现计算两个点(Point)之间的距离(Distance),Distance类的数据成员有Point类的对象。

这里插入代码片
#include<iostream> 
using namespace std;

class Point {
   
 	int x, y;
public:
 	Point(int xx, int yy);
 	Point(Point &p);
 	~Point() {
    cout << "Point's destructor is called" << endl; }
	int getX() {
    return x; }
 	int getY() {
    return y; }
};
Point::Point(int xx, int yy) {
   
	 x = xx;y = yy;
 	cout << "Point's constructor is called" << endl;
}
Point::Point(Point &p) {
   
 	x = p.x;y = p.y;
 	cout << "Point's copy constructor is called" << endl;
}
class Distance {
   
private:
 	Point p1, p2;  // Point类的对象作为Distance类的成员数据,声明顺序先p1后p2
 d	ouble dist;
public:
 	//Distance(Point a, Point b);
 	Distance(Point &a, Point &b);
 	Distance(Distance &d);
 	double getDis() {
    return dist; }
 	~Distance() {
   cout << "Distance's destrutor was called" << endl;}
};
//Distance::Distance(Point a, Point b) :p1(a), p2(b) {   //Point复制构造函数被调用四次
Distance::Distance(Point &a, Point &b) :p1(a), p2(b) {
     //Point复制构造函数被调用二次,传引用就是给变量起别名
 	double x = double(p1.getX() - p2.getX());
 	double y = double(p1.getY() - p2.getY());
 	dist = sqrt(x * x + y * y);
 c	out << "Distance's constructor was called"
  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值