c++ - 使用虚拟重写基类方法不起作用

标签 c++ class oop inheritance overriding

我有 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;


};

类(class)广场

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

 };

在我的主要方法中,我尝试调用方法 computeArea() 的 Square 版本,而不是继续调用方法 computeArea() 的 ShapeTwoD 版本。我在网上读到,放置关键字 virtual 将允许动态确定该方法,因此允许我调用该方法的 Square 版本 computeArea()

为什么会发生这种情况以及如何调用方法 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
 }

最佳答案

这个工作并返回 6 对我来说是预期的:

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

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

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

编辑

include 无关紧要,因为文件会被包含,就好像它们是在您包含它们的地方进行编码一样。

如果您正在使用 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();
}

关于c++ - 使用虚拟重写基类方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19310188/

相关文章:

c++ - QtCreator 和 ncurses

c++ - .get() 重复计算文件末尾的字符

c++ - 如何从基类中的函数调用重载函数?

c++ - 了解 std::end() 的行为和 vector 中的内存分配

java - super(variableName) 之间的区别;和 super.variableName

c++ - 使用 Strcpy_s 复制动态分配的字符数组

c++ - 使用 fork() 与 exec() 创建新进程

java - 在 Linux 终端下运行 Java 类

c++ - 这个声明是什么意思?

c++ - 我的 c++ 类中产生的错误是什么?