github上的每日学习 11

一、 类的组合

问题1、类的组合是什么呢?

基本概念是类中的成员是另一个类的对象,可以在已有的抽象的基础上实现更复杂的抽象。

问题2、组合类的构造函数怎么定义呢?

参数传递,然后用部件类的构造函数来初始化。

问题3、组合类的构造函数设计

原则:不仅要负责本类中的基本类型成员初始化,也要对对象成员初始化。
声明形式:

类名::类名(对象成员所需的形参,本类成员形参):
对象1(参数),对象2(参数),··········
{
//函数体其他语句
}

问题4、初始顺序

按成员定义的顺序,成员对象也是。

问题5、组合类没有构造函数,怎么办?

这就需要部件类都有默认构造函数。

二、 类组合程序举例

线段类:
经过将近一个小时的修改和理解终于会了!
以下是代码和自己加的注释和理解。

#include<iostream>
using namespace std;
//以下是点类,这个类包括了构造函数,复制构造函数,成员横纵坐标和获取坐标函数。
class Point {
public:
    Point(int X, int Y);
    Point(Point& p);
    int getX() { return x; }
    int getY() { return y; }
private:
    int x, y;
};
//点的构造函数,这是定义一个新点必须的,这也是我忘记定义的一个地方。
Point::Point(int X,int Y)
{
    x = X;
    y = Y;
}
//点的复制构造函数:
Point::Point(Point& p)
{
    x = p.x;
    y = p.y;
    cout << "Calling the copy construct of Point" << endl;
}
//线段类,这里包括了构造函数,复制构造函数,获取长度,和 点类的两个对象,也就是两个端点。
class Line {
public:
    Line(Point xp1, Point xp2);
    Line(Line& l);
    double getLen() { return len; }
private:
    Point p1, p2;
    double len;
};
//组合类的构造函数
Line::Line(Point xp1, Point xp2) :p1(xp1), p2(xp2)
{
    cout << "Calling the copy construct of Line" << endl;
    double x = static_cast<double>(p1.getX() - p2.getX());
    double y = static_cast<double>(p1.getY() - p2.getY());
    len = sqrt(x * x + x * y);
}
//组合类的复制构造函数
Line::Line(Line& l) : p1(l.p1), p2(l.p2)
{
    cout << "Calling the copy construct of Line" << endl;
    len = l.len;

}
//主函数
int main() {
    Point myp1(1, 1), myp2(4, 5);//建立Point类对象
    Line line(myp1, myp2);//建立Line类对象
    Line line2(line);//复制构造成为line2.
    cout << "The length of the line Is:";
    cout << line.getLen() << endl;
    cout << "The lengeh of the line2 is:";
    cout << line2.getLen() << endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/zouzou-1/p/12274451.html
今日推荐