关于c++多继承成员函数名冲突的解决方案及调用实质比较
源代码
#include <iostream>
using namespace std;
class Dog
{
public:
virtual void bark() { cout << "Woof!" << endl; }
virtual void eat() { cout << "The dog has eaten." << endl; }
};
class Bird
{
public:
virtual void chirp() { cout << "Chirp!" << endl; }
virtual void eat() { cout << "The bird has eaten." << endl; }
};
class DogBird : public Dog, public Bird
{
};
int main(int argc, char** argv)
{
DogBird myConfusedAnimal;
// myConfusedAnimal.eat(); // BUG! Ambiguous call to method eat()
myConfusedAnimal.Dog::eat() ;
static_cast<Dog>(myConfusedAnimal).eat() ;
}
源码分析
若直接调用myConfusedAnimal.eat(),编译错(“error: request for member ‘eat’ is ambiguous”),用两种方法明确指定具体类成员函数,分别是子类成员函数确定方法和超类确定转换方法。

最低0.47元/天 解锁文章
604

被折叠的 条评论
为什么被折叠?



