【发布时间】:2013-10-11 04:20:40
【问题描述】:
我有 2 个课程:ShapeTwoD 和 Square
Square 派生自 ShapeTwoD
类 ShapeTwoD
class ShapeTwoD
{
public:
ShapeTwoD();
ShapeTwoD(string,bool);
string getName();
void setName(string);
bool getContainsWarpSpace();
void setContainsWarpSpace(bool);
void toString();
virtual double computeArea(){return 2+3.0};
virtual bool isPointInShape(int,int);
virtual bool isPointOnShape(int,int);
private:
string name;
bool containsWarpSpace;
};
班级广场
#include "ShapeTwoD.h"
class Square:public ShapeTwoD
{
public:
virtual double computeArea(){return 2+4.0};
};
在我的主要方法中,我尝试调用方法 computeArea() 的 Square 版本,而不是继续调用方法 computeArea() 的 ShapeTwoD 版本。我在网上读到,放置关键字 virtual 将允许动态确定方法,因此允许我调用方法 computeArea() 的 Square 版本
为什么会发生这种情况以及如何调用方法 computeArea() 的 Square 版本
using namespace std;
#include "Square.h"
int main()
{
Square s;
s.setName("Sponge");
cout<<s.computeArea(); //outputs 5 when i expect it to output 6
}
【问题讨论】:
-
您在生成示例代码时一定已经解决了问题。这个should output 6 经过琐碎的修复。
-
即使没有虚拟,
Square的实例也会调用Square中的computeArea函数。我同意这不是您遇到问题的实际代码。 -
我是否只将类 Square 的头文件包含到 main 方法中,请参阅编辑
-
没关系。无论如何
Square.h包括Shape2D.h。 -
如果包含搞砸了,那么它就不会编译。
标签: c++ class oop inheritance overriding