我正在从这里修改多态性示例以测试多重继承。当我运行以下代码时,我在控制台上打印出一个奇怪的值“15794192”,我预计结果为 20。怎么了?我很欣赏你的意见。
我试图解决由多重继承问题引起的错误,并提出不会产生任何构建错误的代码。我正在讨论的问题可能不是源于多重继承,但我还不确定。网页中引用的原始示例效果很好,不用说。
(环境) Ubuntu 12.04, cmake 2.8.7 在eclipse Indigo上运行
#include <iostream>
using namespace std;
class CPolygon //: public CShape
{
protected:
int width, height;
public:
void set_values(int a, int b)
{
width = a;
height = b;
}
virtual int area(void) =0;
void printarea(void)
{
cout << this->area() << endl;
}
};
class CustomPolygon : public CPolygon
{
public:
int customParam;
void printarea(void)
{
this->CPolygon::printarea();
}
};
class Rectangle : public CPolygon // This class should be concrete.
{
public:
int area(void)
{
return (width * height);
}
void printarea(void)
{
this->CPolygon::printarea();
}
};
class CustomSquare : public CustomPolygon, Rectangle // Concrete class
{
public:
int area()
{
this->Rectangle::area();
}
void printarea(void)
{
this->Rectangle::printarea();
}
void set_values(int a, int b)
{
this->Rectangle::set_values(a, b);
}
};
int main()
{
CustomSquare *cs = new CustomSquare();
cs->CustomSquare::set_values(4, 5);
cs->CustomSquare::printarea();
return 0;
}
(2012 年 8 月 14 日更新)感谢建议,现在我可以避免使用virtual inheritance
. 更新的代码在这里:
#include <iostream>
using namespace std;
class CPolygon
{
protected:
int width, height;
public:
void set_values(int a, int b)
{
width = a;
height = b;
}
virtual int area(void) =0;
void printarea(void)
{
cout << this->area() << endl;
}
};
class CustomPolygon : virtual public CPolygon
{
public:
int customParam;
};
class Rectangle : virtual public CPolygon
{
public:
int area(void)
{
return (width * height);
}
};
class CustomSquare : public CustomPolygon, Rectangle
{
};
int main()
{
CustomSquare *cs = new CustomSquare();
cs->CustomSquare::set_values(4, 5);
cs->CustomSquare::printarea();
return 0;
}