帮我看看这个代码出什么错了 (c++动态多态)
#include<iostream>using namespace std;
class Shape//形状类
{
public:
double calcArea()
{
cout<<"calcArea"<<endl;
return 0;
}
};
class Circle:public Shape //公有继承自形状类的圆形类
{
public:
Circle(double r);
double calcArea();
private:
double m_dR;
};
double Circle::calcArea()
{
return 3.14*m_dR*m_dR;
}
class Rect:public Shape //公有继承自形状类的矩形类
{
public:
Rect(double width,double height);
double calcArea();
private:
double m_dWidth;
double m_dHeight;
};
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;
}
本帖最后由 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;
}
编译也通过了 但是运行结果是空格?? 人造人 发表于 2018-6-23 11:09
谢谢,已经改正了,但是新的问题又出现了····
三楼拜托大神了 juezuo 发表于 2018-6-23 11:18
谢谢,已经改正了,但是新的问题又出现了····
三楼拜托大神了
有什么问题吗? 人造人 发表于 2018-6-23 11:36
有什么问题吗?
可以通过编译,但是运行结果什么都没有 juezuo 发表于 2018-6-23 11:59
可以通过编译,但是运行结果什么都没有
对呀,这个程序就是什么都不输出呀
你想要输出 calcArea 吗? #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);
Shape *shape3 = new Shape();
shape1->calcArea();
shape2->calcArea();
shape3->calcArea();
delete shape1;
delete shape2;
delete shape3;
return 0;
}
人造人 发表于 2018-6-23 12:52
谢谢大神!!!{:10_254:}
页:
[1]