him*_*ims 15 c++ inheritance multiple-inheritance
最近我参加了一次C++技术访谈:在那次采访中我问了一个我无法回答的问题:即使我尝试上网和一些论坛但无法得到答案,请参阅下面的代码片段:
using namespace std;
class Base1
{
public:
Base1()
{
cout << "Base1 constructor..." << endl;
}
~Base1()
{
cout << "Base1 Destructor..." << endl;
}
};
class Base2
{
public:
Base2()
{
cout << "Base2 constructor..." << endl;
}
~Base2()
{
cout << "Base2 Destructor..." << endl;
}
};
class Derived : public Base1, public Base2
{
public:
Derived()
{
cout << "Derived constructor...." << endl;
}
~Derived()
{
cout << "Derived Destructor..." << endl;
}
};
int main()
{
cout << "Hello World" << endl;
Base1 b1; Base2 b2;
Derived d1;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
描述:有两个名为Base1和Base2的基类和一个名为Derived的派生类.Derived是从Base1和Base2继承的多个.
问题:我希望Derived只能从一个类继承,而不是从两个类继承.如果开发人员将尝试从这两个类继承:那么错误应该生成:让我总结一下:
注意:你能否回答这个问题:我真的不确定这是否可行.还有一件事:这不是钻石问题.
谢谢.
egu*_*gur 27
在两个具有不同返回类型的基础中声明纯虚函数:
class B1 {
virtual void a() = 0;
};
class B2 {
virtual int a() = 0; // note the different return type
};
Run Code Online (Sandbox Code Playgroud)
从两者都继承是不可能的.
class D : public B1, public B2 {
public:
// virtual void a() {} // can't implement void a() when int a() is declared and vice versa
virtual int a() {}
};
int main(void) {
D d; // produces C2555 error
return 0;
}
Run Code Online (Sandbox Code Playgroud)
产生此错误: