【问题标题】:overriding base class method using virtual does not work使用 virtual 覆盖基类方法不起作用
【发布时间】: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


【解决方案1】:

这项工作并按预期返回6

class ShapeTwoD {
public:
    virtual double computeArea(){return 2+3.0;};
};

class Square:public ShapeTwoD
{
public:
    virtual double computeArea(){return 2+4.0;};    
};

我必须在computeArea 中的} 之前添加;,您是否错过了示例中的内容?否则,您可能没有运行最新版本。

编辑

包含无关紧要,因为文件被包含,就好像它们在您包含它们的位置编码一样。

如果您使用的是gcc/g++(但我猜其他编译器也有类似的选项),您可以使用选项-E 来查看预编译阶段后.c/.cpp 文件的结果(也是#include

g++ -c -E test.cpp

结果如下:

# 2 "test.cpp" 2

using namespace std;

# 1 "square.h" 1
# 1 "shapetwo.h" 1
class ShapeTwoD
{
public:
 virtual double computeArea(){return 2+3.0;};
};
# 2 "square.h" 2

class Square:public ShapeTwoD
{
public:
 virtual double computeArea(){return 2+4.0;};
};
# 6 "test.cpp" 2

int main() {
 Square s;
 cout<<s.computeArea();
}

【讨论】:

  • 对我也有用 - 我什至将工作代码放在键盘上:codepad.org/p5PaiKHh
  • 我认为这与我只包含不同类的头文件这一事实有关
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-03
  • 1970-01-01
  • 1970-01-01
  • 2011-11-03
  • 2016-12-28
  • 2019-01-13
相关资源
最近更新 更多