一篇文章带你了解C++面向对象编程--继承

C++ 面向对象编程 —— 继承

"Shape" 基类

class Shape {
public:
	Shape() {		// 构造函数
		cout << "Shape -> Constructor" << endl;
	}
	~Shape() {		// 析构函数
		cout << "Shape -> Destructor" << endl;
	}
	void Perimeter() {		// 求 Shape 周长
		cout << "Shape -> Perimeter" << endl;
	}
	void Area() {		// 求 Shape 面积
		cout << "Shape -> Area" << endl;
	}
};

"Circle" 派生类

“Circle” 类继承于 “Shape” 类

class Circle : public Shape {
public:
	Circle(int radius) :_r(radius) {
		cout << "Circle -> Constructor" << endl;
	}
	~Circle() {
		cout << "Circle -> Destructor" << endl;
	}
	void Perimeter() {
		cout << "Circle -> Perimeter : "
			<< 2 * 3.14 * _r << endl;		// 圆周率取 3.14
	}
	void Area() {
		cout << "Circle -> Perimeter : "
			<< 3.14 * _r * _r << endl;		// 圆周率取 3.14
	}
private:
	int _r;
};

"Rectangular" 派生类

“Rectangular” 类继承于 “Shape” 类

class Rectangular : public Shape {
public:
	Rectangular(int length, int width) :_len(length), _wid(width) {
		cout << "Rectangular -> Contructor" << endl;
	}
	~Rectangular() {
		cout << "Rectangular -> Destructor" << endl;
	}
	void Perimeter() {
		cout << "Rectangular -> Perimeter : "
			<< 2 * (_len + _wid) << endl;
	}
	void Area() {
		cout << "Rectangular -> Area : "
			<< _len * _wid << endl;
	}
private:
	int _len;
	int _wid;
};

"main()" 函数

int main()
{
	/*  创建 Circle 类对象 cir  */
	Circle cir(3);
	cir.Perimeter();
	cir.Area();
	cout << endl;

	/*  创建 Rectangle 类对象 rec  */
	Rectangular rec(2, 3);
	rec.Perimeter();
	rec.Area();
	cout << endl;

	return 0;
}

运行结果

5439A245-5CA2-DBF4-56D6-E559AEADA0AC.png

  1. 创建派生类对象 :

    基类的 Constructor 先执行,然后执行子类的 Constructor

  2. 析构派生类对象 :

    派生类的 Destructor 先执行,然后执行基类的 Destructor

收藏 (0)
评论列表
正在载入评论列表...
我是有底线的
为您推荐
    暂时没有数据