C++虚继承演示
在继承中如果出现:
这种情况,B和C都继承了A,D继承了B、C
在D中访问A的成员会出现:
这样的警告
是因为在继承时A出现两条分支:ABD、ACD
编译器不知道访问的A中的元素是经过B继承还是C继承
所以B、C在继承A时要用到虚继承virtual
即:
class B : virtual public A
class C : virtual public A
#include <iostream>
using namespace std;
class A
{
private:
int m_a;
public:
A(int a);
void print();
};
A::A(int a)
{
m_a = a;
}
void A::print()
{
cout << "m_a = " << m_a << endl;
}
class B : virtual public A
{
private:
int m_b;
public:
B(int a, int b);
void print();
};
B::B(int a, int b) : A(a)
{
m_b = b;
}
void B::print()
{
cout << "m_b = " << m_b << endl;
}
class C : virtual public A
{
private:
int m_c;
public:
C(int a,int c);
void print();
};
C::C(int a, int c) : A(a)
{
m_c = c;
}
void C::print()
{
cout << "m_c = " << m_c << endl;
}
class D : public B, public C
{
private:
int m_d;
public:
D(int a, int b, int c, int d);
void print();
};
D::D(int a, int b, int c, int d) : A(a), B(a, b), C(a, c)
{
m_d = d;
}
void D::print()
{
A::print();
B::print();
C::print();
cout << "m_d = " << m_d << endl;
}
int main()
{
D d(1, 2, 3, 4);
d.print();
return 0;
}
运行结果:
原文地址:https://blog.csdn.net/2303_78630464/article/details/143628809
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!