内嵌对象

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

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

  2. 在建立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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值