首页 > 编程语言 > 一篇文章带你了解C++面向对象编程--继承
2022
08-16

一篇文章带你了解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;
}

运行结果

这张图不好看

1.创建派生类对象 :

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

2.析构派生类对象 :

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

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注自学编程网的更多内容!

编程技巧