我只是想知道是否所有的虚函数都必须是常量?
我对它们有一些问题,因为当我想打印它们时,该区域总是为我的正方形返回 0。如果有人能启发我,将不胜感激。
shapetwod.h
class ShapeTwoD
{
protected:
string name, warpSpace;
bool containsWarpSpace;
public:
//constructor
ShapeTwoD();
ShapeTwoD(string, bool);
//accessors/set function
void setName(string);
//mutator/get function
string getName();
//methods
virtual double computeArea();
virtual void view();
};
shapetwod.cpp
ShapeTwoD::ShapeTwoD()
{
string name = "";
}
ShapeTwoD::ShapeTwoD(string ShapeName)
{
name = ShapeName;
}
void ShapeTwoD::setName(string shapeName)
{
name=shapeName;
}
string ShapeTwoD::getName()
{
return name;
}
double ShapeTwoD::computeArea()
{
return 0;
}
void ShapeTwoD::view()
{
cout << "Area is: " << endl;
}
平方.h
class Square:public ShapeTwoD
{
private:
int xVal,yVal;
int length, breath;
double area;
public:
Square();
Square(string, int, int, double);
//acessor method
//int getSquareDetails();
int getxCord();
int getyCord();
double getArea();
virtual double computeArea();
void view();
int xvalue[4];
int yvalue[4];
};
正方形.cpp
Square::Square()
{
xVal = 0;
yVal = 0;
area = 0;
}
Square::Square(string ShapeName, bool warpspace, int xval, int yval, double areas):ShapeTwoD(ShapeName, warpspace)
{
xVal = xval;
yVal = yval;
area = areas;
}
void Square::setSquareCord()
{
for (int i=0; i<4; i++)
{
cout << "Please enter x-ordinate of pt " << i+1 << ": ";
cin >> xVal;
xvalue[i] = xVal;
cout << endl;
cout << "Please enter y-ordinate of pt " << i+1 << ": ";
cin >> yVal;
yvalue[i] = yVal;
cout << endl;
}
}
double Square::computeArea()
{
int xmax = xvalue[1];
int xmin = xvalue[1];
int ymax = yvalue[1];
int ymin = yvalue[1];
for(int i=0; i<4; i++)
{
if(xvalue[i]>xmax)
{
xmax = xvalue[i];
}
else if(xvalue[i]<xmin)
{
xmin = xvalue[i];
}
}
for(int i=0; i<4; i++)
{
if(yvalue[i]>ymax)
{
ymax = yvalue[i];
}
else if(yvalue[i]<ymin)
{
ymin = yvalue[i];
}
}
length = xmax - xmin;
breath = ymax - ymin;
area = length * breath;
return (area);
}
int Square::getxCord()
{
return xVal;
}
int Square::getyCord()
{
return yVal;
}
double Square::getArea()
{
return area;
}
void Square::view()
{
cout << "Name: " << getName() << endl;
cout << "Area is: " << area << endl;
}
对不起,但我真的不知道如何分阶段提出我的问题。我实际上在这里使用多态性和虚拟函数,而我的 computeArea 和 view 函数是虚拟的。
所以在我的“view”函数下的square.cpp中,程序总是会返回0,我不知道为什么会这样..
这就是我调用视图函数的方式。不确定它是否在这里有帮助..
void Shape2DLink::InputSensor()
{
string shape,type;
cout<<endl<<"\n"<<"[ Input sensor data ]"<<endl;
cout << "Please enter name of shape: " << endl;
cin >> shape;
shape2D.setName(shape);
cout << "Please enter special type : " << endl;
cin >> type;
shape2D.setWarpSpace(type);
if(shape == "Square")
{
square.setSquareCord();
square.computeArea();
square.isPointOnShape();
square.isPointInShape();
Square *mySquare = new Square;
shapeobject.push_back(mySquare);
//shapeobject.push_back( new Square );
}
}
void Shape2DLink::Display()
{
vector<ShapeTwoD*>::iterator vectorIt = shapeobject.begin();
while(vectorIt != shapeobject.end())
{
(*vectorIt)->view();
vectorIt++;
}
}