内嵌对象

    科技2022-09-05  136

    Circle类中包含有Point类的对象成员表示圆心。

    类包含对象成员的时候,类的构造函数要实现对象成员的初始化。

    在建立Circle类的对象时调用Point类的构造函数:

    如果Point类有定义默认构造函数,在执行Circle类的构造函数体之前,内嵌对象成员center自动调用Point类的默认构造函数进行初始化。如果Point类没有定义默认构造函数,则必须使用初始化列表的方式指定初始化式来初始化内嵌对象成员center。 #include <iostream> #include <string.h> using namespace std; class Point{ private: double x; double y; public: Point(double x = 0, double y = 0) :x(x), y(y){} Point(Point &other) :x(other.x),y(other.y){} double getx(){ return x; } double gety(){ return y; } void setx(double x){ this->x = x; return ; } void sety(double y){ this->y = y; return ; } }; class Circle{ private: double radius; Point center; public: //无参构造函数 Circle():radius(0), center(0, 0){ cout << "无参构造函数"<< endl; } //有参构造函数 Circle(double radius ,Point center) :radius(radius), center(center.getx(), center.gety()){ cout << "有参构造函数"<< endl; } //复制构造 Circle(Circle &other) :radius(other.radius), center(other.center.getx(), other.center.gety()){ cout << "复制构造函数"<< endl; } //赋值运算符重载 Circle &operator = (Circle &other){ radius = other.radius; center.setx(other.center.getx()); center.sety(other.center.gety()); cout << "赋值运算符重载" << endl; } //显示函数 void print(){ cout << "cente:(" << center.getx() << ',' << center.gety() << ')' << endl; cout << "radius:"<< radius <<endl; return ; } }; int main(void){ Point p1(6, 6); Circle c1(1, p1); c1.print(); Circle c2 = c1; c2.print(); Circle c3; c3 = c2; c3.print(); return 0; }
    Processed: 0.014, SQL: 9