2016-05-19 14:13

# 关于多重继承和虚基类的问题

#include <iostream>
using namespace std;

class Point2D
{
protected:
double x;
double y;
public:
Point2D() { x = 0; y = 0; }
Point2D(double a, double b)
{
x = a;
y = b;
}
virtual void show()
{
cout << "The 2D point is:(" << x << ',' << y << ')'<<endl;
}
};

class Circle:virtual public Point2D
{
protected:
public:
Circle() { radius = 0; }
Circle(double a, double b, double c) :Point2D(a, b)
{
}
virtual void show()
{
cout << "The center of circle is:(" << x << ',' << y << ')' << endl;
}
};

class Point3D :virtual public Point2D
{
protected:
double z;
public:
Point3D(double a, double b, double c) :Point2D(a, b)
{
z = c;
}
virtual void show()
{
cout << "The 3D point is:(" << x << ',' << y << ',' << z << ')' << endl;
}
};

class Sphere :public Circle, public Point3D
{
public:
Sphere(double a, double b, double c, double r) :Point3D(a, b, c)
{
}
virtual void show()
{
cout << "The center of sphere is:(" << x << ',' << y << ','<<z<<')' << endl;
}
};

int main()
{
Point2D p1(1, 1);
Circle c1(1, 2, 2);
Point3D p2(1.5, 2.5, 3.5);
Sphere s1(1, 2, 3, 4);
//p1 = c1;
Point2D* pointer = &p1;
pointer->show();
pointer = &c1;
pointer->show();
pointer=&p2;
pointer->show();
pointer = &s1;
pointer->show();
system("pause");
return 0;
}
• 点赞
• 写回答
• 关注问题
• 收藏
• 邀请回答

#### 2条回答默认 最新

• Valtava 2016-05-19 14:54
已采纳

这里Point2D是Circle和Point3D的父类，会早于它们初始化，由于你没有显式的指定构造函数参数，因此这里Point2D直接默认构造成为（0，0），此时Point2D的构造已经完成，因此Point3D的构造函数中
Point3D(double a, double b, double c) : Point2D(a,b)
这部分会被跳过，于是x和y便保留了默认构造时候的（0,0）。
你可以显式的初始化所有基类

class Sphere :public Circle, public Point3D
{
public:
Sphere(double a, double b, double c, double r)
: Point2D(a, b)
, Circle(a, b, r)
, Point3D(a, b, c)
{
}
virtual void show()
{
cout << "The center of sphere is:(" << x << ',' << y << ',' << z << ')' << endl;
}
};

点赞 评论
• Robot-S 2016-05-19 14:22

#include <iostream>
using namespace std;
class A
{
public:
int a;
};

class A1: public A
{

};
class A2: public A1
{

};
class B1: public A
{

};
class B2: public B1......
答案就在这里：有关多重继承虚基类的问题
----------------------Hi，地球人，我是问答机器人小S，上面的内容就是我狂拽酷炫叼炸天的答案，除了赞同，你还有别的选择吗？

点赞 评论