继承后,我在某些方法上遇到麻烦。(对我来说)很难说出确切的问题出在哪里,但我将尝试通过示例来揭露。
最小代码:
#include <iostream>
class A
{
public:
A() {};
A(int x):val(x)
{
std::cout << "A constructor work" << std::endl;
}
int get()
{
std::cout << "Get A work" << std::endl;
return val;
}
protected:
int val;
};
class B: protected A
{
public:
B(int x) :A(x)
{
std::cout << "B constructor work" << std::endl;
test();
}
int get()
{
std::cout << "Get B work" << std::endl;
return A::get();
}
protected:
void test()
{
if (A::val == 0)
{
std::cout << "Test B work" << std::endl;
A::val = 1;
}
}
};
class C : protected A
{
public:
C() {};
C(int x) :A(x)
{
std::cout << "C constructor work" << std::endl;
test();
}
int get()
{
std::cout << "Get C work" << std::endl;
return A::get();
}
protected:
void test()
{
std::cout << "Test C work" << std::endl;
if (A::val != 0)
{
A::val += 2;
}
}
};
class D : private B, private C
{
public:
D(int x):B(x)
{
std::cout << "D constructor work" << std::endl;
C::test();
}
int get()
{
std::cout << "Get D work" << std::endl;
return B::get();
}
};
int main()
{
D d(0);
std::cout << d.get() << std::endl;
}
Output:
**A constructor work
B constructor work
Test B work
D constructor work
Test C work
Test C extra work
Get D work
Get B work
Get A work
1**
我希望val最终等于3,但是那样行不通。谢谢您的详细答复。
[您的class D
包含两个A
对象-一个由B
继承的对象和一个由C
继承的对象
当您调用C::test()
时,在A
中更改了C
对象。
[当调用D::get()
时-调用B::get()
时,将检查A
中B
对象的值。
解决此问题的一种方法是通过virtual inheritance。但是,在您了解多重继承的工作原理之前,不要想弄混它。