什么是继承
继承允许我们依据另一个类(基类)来定义一个类(子类),并复用基类的成员变量和成员函数。
C++的继承如何实现
-
基本语法
class derived-class: access-specifier base-class
-
main.cpp
#include<iostream>
#include "Shape.cpp"
int main(){
Rectangle rec;
rec.setWidth(10);
rec.setHeight(5);
cout << "area is: " << rec.getArea() << endl;
}
- Shape.cpp
class Shape{
protected:
int width;
int height;
public:
void setWidth(int w){
width = w;
}
void setHeight(int h){
height = h;
}
};
class Rectangle:public Shape{
public:
int getArea(){
return width*height;
}
};
访问修饰符的作用
访问修饰符的类型
- public
- protected
- private
访问修饰符的访问控制效果
访问 | public | protected | private |
---|---|---|---|
同一个类 | yes | yes | yes |
派生类 | yes | yes | no |
外部的类 | yes | no | no |
访问修饰符控制下的继承类型
- public 继承:
-
- public -> public
-
- protected->protected
-
- private->private
- protected 继承:
-
- public -> protected
-
- protected->protected
-
- private->private
- private 继承:
-
- public -> private
-
- protected->private
-
- private->private