C++ 继承与派生

1、继承与派生

继承:子继承父

派生:子继承父,但是又多了一些父没有的

2、继承的方式

公有继承、保护继承、私有继承   C++默认为私有继承

访问特性可以通过派生类对基类的继承方式进行控制

Access public protected private
members of the same class yes yes yes
members of derived class yes yes no
not members yes no no
#include<iostream>
using namespace std;
class Ploygon{
protected:
	int width, height;
public:
	void set_values(int a, int b){
		width = a;
		height = b;
	}
};
class Rectangle : public Ploygon{
public:
	int area(){
		return width * height;
	}
};
class Triangle : public Ploygon{
public:
	int area(){
		return width * height / 2;
	}
};
int main()
{
	Rectangle rect;
	Triangle trgl;
	rect.set_values(4, 5);
	trgl.set_values(4, 5);
	cout << rect.area() << endl;
	cout << trgl.area() << endl;
}

3、派生类都继承了那些:

公有继承的继承了所有,除了:

构造函数和析构函数

赋值运算符重载

友元函数

私有成员

继承中构造函数和析构函数不被继承,但是会被子类自动调用,自动调用的为默认的构造函数和析构函数,如果没有指定

#include<iostream>
using namespace std;
class Mother{
public:
	Mother(){ cout << "Mother no parameters" << endl; }
	Mother(int a){ cout << "Mother : int parameter" << endl; }
};
class Daughter :public Mother{
public:
	Daughter(int a){
		cout << "Daugher : int parameter\n";
	}
};
class Son :public Mother{
public:
	Son(int a) :Mother(a){
		cout << "Son: int parameter\n ";
	}
};
int main()
{
	Daughter kelly(0);
	Son bud(0);
	return 0;
}

4、继承多个类

#include<iostream>
using namespace std;
class Polygon{
protected:
	int width, height;
public:
	Polygon(int a, int b) :width(a), height(b){ cout << "father\n"; }
};
class Output{
public:
	static void print(int i);
};
void Output::print(int i){
	cout << i << endl;
}
class Rectangle :public Polygon, public Output{
public:
	Rectangle (int a, int b) : Polygon(a,b){}
	int area(){ return width * height; }
};
class Triangle : public Polygon, public Output{
public:
	Triangle(int a, int b) :Polygon(a, b){}
	int area(){
		return width * height / 2;
	}
};
int main()
{
	Rectangle rect(4, 5);
	Triangle trgl(4, 5);
	rect.print(rect.area());
	Triangle::print(trgl.area());
}

 

猜你喜欢

转载自blog.csdn.net/qq_20599225/article/details/82858402