第二节 · 宗族的继承 · 基类与派生类
// 基类(父类)
class Animal
{
protected:
string name;
public:
Animal(const string& n) : name(n) {}
void eat()
{
cout << name << " is eating." << endl;
}
};
// 派生类(子类)
class Dog : public Animal
{
public:
Dog(const string& n) : Animal(n) {} // 调用基类构造函数
void bark()
{
cout << name << " says: Woof!" << endl;
}
};
int main()
{
Dog d("Buddy");
d.eat(); // 继承自 Animal
d.bark(); // Dog 自己的方法
return 0;
}继承方式
基类 public
基类 protected
基类 private
习题
Last updated