欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C/C++中组合详解及其作用介绍

程序员文章站 2022-06-25 09:35:28
目录概述组合 (composition) 指在一个类中另一类的对象作为数据成员.案例在平面上两点连成一条直线, 求直线的长度和直线中点的坐标.要求: 基类: dot 派生类: line (...

概述

组合 (composition) 指在一个类中另一类的对象作为数据成员.

C/C++中组合详解及其作用介绍

案例

在平面上两点连成一条直线, 求直线的长度和直线中点的坐标.
要求:

  • 基类: dot
  • 派生类: line (同时组合)
  • 派生类 line 从基类 dot 继承的 dot 数据, 存放直线的中点坐标
  • line 类再增加两个 dot 对象, 分别存放两个端点的坐标

dot 类:

#ifndef project5_dot_h
#define project5_dot_h

#include <iostream>
using namespace std;

class dot {
public:
    double x, y;
    dot(double a, double b) : x(a), y(b) {};
    void show() {
        cout << "x: " << x << endl;
        cout << "y: " << y << endl;
    };
};

#endif //project5_dot_h

line 类:

#ifndef project5_line_h
#define project5_line_h

#include "dot.h"

class line : public dot {
private:
    dot d1;
    dot d2;
public:
    line(const dot &d1, const dot &d2) : dot(0, 0), d1(d1), d2(d2) {
        x = (d1.x + d2.x) / 2;
        y = (d1.y + d2.y) / 2;
    }

    void show(){
        dot::show();
        cout << "dot1: (" << d1.x << ", " << d1.y << ")" << endl;
        cout << "dot2: (" << d2.x << ", " << d2.y << ")" << endl;
    }
};

#endif //project5_line_h

main:

#include <iostream>
#include "dot.h"
#include "line.h"
using namespace std;

int main() {
    double a, b;
    cout << "input dot1: \n";
    cin >> a >> b;
    dot dot1(a,b);
    cout << "input dot2: \n";
    cin >> a >> b ;
    dot dot2(a,b);
    line l1(dot1, dot2);
    l1.show();

    return 0;
}

输出结果:

input dot1:
1 2
input dot2:
4, 6
x: 2.5
y: 1
dot1: (1, 2)
dot2: (4, 0)

总结

  • 类的组合和继承都是重用的重要方式, 可以有效地利用已有类的资源
  • 继承是纵向的, 组合是横向的. 通过继承, 我们从基类得到了数据成员. 通过组合, 从别的类得到了成员, 有效地组织和利用现有的类, 减少工作量
  • 如果类 a 和类 b 毫不相关, 不可以为了使 b 的功能更多些而让 b 继承 a 的功能
  • 如果类 b 有必要使用类 a 的功能. 当 b 是 a 的一种的时候我们使用继承, 当 b 是 a 的一部分时, 我们使用组合

到此这篇关于c/c++中组合详解及其作用介绍的文章就介绍到这了,更多相关c++组合内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!