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