我错过了什么,还是我发现了 Visual Studio 错误?
除了错误,使用这种类型的继承是好还是坏?
GCC 4.9.0 产生了我的预期结果:
base.getProperty() 1
otherBase.getProperty() 2
derivedA.getProperty() 1
derivedB.getProperty() 2
但是,VS 2015 (CTP 6) 和 VS 2013 (Update 5 CTP) 都产生了我认为不正确的结果:
base.getProperty() 1
otherBase.getProperty() 2
derivedA.getProperty() 1
derivedB.getProperty() 1
将“class derivedClassB:public derivedClassA,otherBaseClass {”更改为“class derivedClassB:public otherBaseClass,derivedClassA {”会产生我预期的结果。我可能会遗漏一些东西,但是尽管继承自的类的顺序会影响初始化顺序,但我认为它不会影响使用哪个模棱两可的函数——尤其是当有一个 using 语句来澄清否则存在的歧义时。
#include <iostream>
using namespace std;
class baseClass {
public:
virtual int getProperty() {
return 1;
}
};
class otherBaseClass : public baseClass {
public:
virtual int getProperty() {
return 2;
}
};
class derivedClassA : public baseClass {
public:
void someUniqueThing() {
cout << "someUniqueThing" << endl;
}
};
class derivedClassB : public derivedClassA, otherBaseClass {
public:
using otherBaseClass::getProperty;
};
int main() {
baseClass base;
cout << "base.getProperty() " << base.getProperty() << endl;
otherBaseClass otherBase;
cout << "otherBase.getProperty() " << otherBase.getProperty() << endl;
derivedClassA derivedA;
cout << "derivedA.getProperty() " << derivedA.getProperty() << endl;
derivedClassB derivedB;
cout << "derivedB.getProperty() " << derivedB.getProperty() << endl;
}