我正在学习C++,我正在尝试实现一个简单的c++程序来创建一个抽象类,如下所示:请解释为什么编译后会出现这个错误?请用简单的语言来解释,我不是术语专家,而且还在学习OOPS的概念。预先谢谢(代码和错误)
代码:
/*
* shape.cpp
*
* Created on: Mar 9, 2014
* Author: Drix
*/
#include <iostream>
using namespace std;
class shape{
public:
virtual void Draw(void)=0;
};
class circle:public shape{
public:
void Draw(double radius){
radii = radius;
cout << "The radius of the circle is " << radii<<endl;
}
private:
double radii;
};
class square:public shape{
public:
void Draw(double side){
s = side;
cout << "The length of side of sqare is " << s<<endl;
}
private:
double s;
};
int main(){
cout <<"Welcome to shape drwaing program"<<endl;
cout <<"Enter 1 to draw a sqare or 2 to draw a circle"<<endl;
int input;
cin>>input;
if(input == 1)
{
cout << "Please enter the radius of the circle: ";
double radius;
cin >> radius;
circle *p = new circle;
p->Draw(radius);
}
if(input == 2)
{
cout << "Please enter the length of the side of a square: ";
double side;
cin >> side;
square *t = new square;
t->Draw(side);
}
}错误:
10:58:15 **** Incremental Build of configuration Debug for project Shape ****
Info: Internal Builder is used for build
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o shape.o "..\\shape.cpp"
..\shape.cpp: In function 'int main()':
..\shape.cpp:51:19: error: cannot allocate an object of abstract type 'circle'
..\shape.cpp:18:7: note: because the following virtual functions are pure within 'circle':
..\shape.cpp:14:15: note: virtual void shape::Draw()
..\shape.cpp:59:20: error: cannot allocate an object of abstract type 'square'
..\shape.cpp:28:7: note: because the following virtual functions are pure within 'square':
..\shape.cpp:14:15: note: virtual void shape::Draw()
10:58:16 Build Finished (took 884ms)发布于 2014-03-09 17:15:51
问题如下:在shape类中,您声明了不接受参数的绘制:
virtual void Draw(void)=0;而子类circle和square的draw需要一个double:
void Draw(double radius)在circle中,我认为radius应该传递给构造函数(可能还有类似中心的东西),而绘图不应该接受任何东西。例如:
class circle:public shape{
private:
double radii;
public:
circle(double radius) radii(radius) {};
void Draw(){
cout << "The radius of the circle is " << radii<<endl;
}
};然后你用它作为
circle *p = new circle(radius);
p->Draw();或者如果您不需要动态分配:
circle c(radius);
c.Draw()当然,square类也有同样的问题。
发布于 2014-03-09 17:13:06
绘制方法的参数不匹配。
形状:
virtual void Draw(void)=0;在圆圈和正方形中:
void Draw(double radius)如果您想拥有虚拟方法,则参数必须匹配。
发布于 2014-03-09 17:15:01
这种方法的形状应该是(不需要空的)。
class shape{
public:
virtual void Draw()=0;
};当您声明循环时,您需要一个Draw方法(即没有半径位的方法)。
https://stackoverflow.com/questions/22285261
复制相似问题