本帖最后由 juezuo 于 2018-6-23 11:22 编辑
补了构造函数之后的新问题
在原来的代码基础上补上 虚函数
新代码#include<iostream>
using namespace std;
class Shape//形状类
{
public:
virtual double calcArea() //虚函数
{
cout<<"calcArea"<<endl;
return 0;
}
};
class Circle:public Shape //公有继承自形状类的圆形类
{
public:
Circle(double r);
virtual double calcArea(); //虚函数
private:
double m_dR;
};
Circle::Circle(double r):m_dR(r){
}
double Circle::calcArea()
{
return 3.14*m_dR*m_dR;
}
class Rect:public Shape //公有继承自形状类的矩形类
{
public:
Rect(double width,double height);
virtual double calcArea(); //虚函数
private:
double m_dWidth;
double m_dHeight;
};
Rect::Rect(double width,double height):m_dWidth(width), m_dHeight(height){
}
double Rect::calcArea()
{
return m_dWidth*m_dHeight;
}
int main()
{
Shape *shape1=new Circle(4.0);
Shape *shape2=new Rect(3.0,5.0);
shape1->calcArea();
shape2->calcArea();
return 0;
}
编译也通过了 但是运行结果是空格?? |