在 C++ 多重继承中如何选择将继承哪个基础 class 方法?
How in C++ multiple inheritance choose of which base class method will be inherited?
考虑以下简单示例:
#include <iostream>
using namespace std;
class A {
public:
virtual void foo() {
cout<<"A"<<endl;
}
};
class B: public virtual A {
public:
virtual void foo(){
cout<<"B"<<endl;
}
};
class C : public virtual A {
public:
virtual void foo(){
cout<<"C"<<endl;
}
};
class D : public B, public C {
public:
void print(){
foo();
}
};
int main () {
D d;
d.print();
return 0;
}
此代码无效,因为对 foo 的调用不明确。但问题是:
如何定义 类 应该继承哪些方法?如果我有这样的机会呢?
消除函数调用的歧义。举个例子:
class A { virtual void foo(); };
class B { virtual void foo(); };
class C : public A ,public B { void foo(); };
要从 A、B 甚至从 child class 调用 foo:C do
C *obj = new C;
obj->foo();
obj->A::foo();
obj->B::foo();
Source/inspiration: http://www.cprogramming.com/tutorial/multiple_inheritance.html
考虑以下简单示例:
#include <iostream>
using namespace std;
class A {
public:
virtual void foo() {
cout<<"A"<<endl;
}
};
class B: public virtual A {
public:
virtual void foo(){
cout<<"B"<<endl;
}
};
class C : public virtual A {
public:
virtual void foo(){
cout<<"C"<<endl;
}
};
class D : public B, public C {
public:
void print(){
foo();
}
};
int main () {
D d;
d.print();
return 0;
}
此代码无效,因为对 foo 的调用不明确。但问题是:
如何定义 类 应该继承哪些方法?如果我有这样的机会呢?
消除函数调用的歧义。举个例子:
class A { virtual void foo(); };
class B { virtual void foo(); };
class C : public A ,public B { void foo(); };
要从 A、B 甚至从 child class 调用 foo:C do
C *obj = new C;
obj->foo();
obj->A::foo();
obj->B::foo();
Source/inspiration: http://www.cprogramming.com/tutorial/multiple_inheritance.html