C++中私有继承的例子
时间: 2024-03-10 08:51:08 浏览: 12
下面是一个使用私有继承的简单例子:
```
#include <iostream>
class Animal {
public:
void eat() {
std::cout << "Animal is eating" << std::endl;
}
};
class Cat : private Animal {
public:
void eat() {
Animal::eat(); // 调用基类的 eat() 函数
std::cout << "Cat is eating" << std::endl;
}
};
int main() {
Cat cat;
cat.eat(); // 只能通过派生类的成员函数调用基类的 eat() 函数
// cat.Animal::eat(); // 错误,基类的 eat() 函数是私有的,无法访问
return 0;
}
```
在上面的例子中,Cat 类私有继承了 Animal 类,这意味着 Animal 类的公有和保护成员都变成了 Cat 类的私有成员。在 Cat 类中,我们定义了一个 eat() 函数,它调用了基类 Animal 的 eat() 函数。由于 Animal 类的 eat() 函数是私有的,无法从外部访问,所以只能通过 Cat 类的成员函数来调用它。在 main() 函数中,我们创建了一个 Cat 对象并调用了它的 eat() 函数,它会先输出 "Animal is eating",然后再输出 "Cat is eating"。