继承的语法
利用继承可以减少重复代码出现;
语法:class 子类 : 继承方式 父类 {};
// 基类(父类)
class Animal {
public:
void eat() { cout << "Animal is eating" << endl; }
void sleep() { cout << "Animal is sleeping" << endl; }
};
// 派生类(子类)
class Dog : public Animal {
// Dog 继承自 Animal
public:
void bark() { cout << "Dog is barking" << endl; }
};
int main() {
Dog myDog;
myDog.eat(); // 继承自 Animal
myDog.sleep(); // 继承自 Animal
myDog.bark(); // Dog 自己的方法
return 0;
}
继承方式
不同的继承方式决定了基类成员在派生类中的访问权限;
- 公共继承(class 子类 : public 父类)
- 保护继承(class 子类 : protected 父类)
- 私有继承(class 子类 : private 父类)
三者区别:
| 基类成员权限 | public 继承 | protected 继承 | private 继承 |
|---|---|---|---|
| public | public | protected | private |
| protected | protected |

