我正在学习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)
答案 0 :(得分:2)
问题如下:在类shape
中,您将draw声明为不带参数:
virtual void Draw(void)=0;
而子类circle
和square
期望draw
期望加倍:
void Draw(double radius)
在circle
中,我认为radius
(可能还有像中心这样的东西)应该传递给构造函数,而draw应该不接受任何东西。例如:
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
也存在同样的问题。
答案 1 :(得分:1)
Draw方法的参数不匹配。
形状:
virtual void Draw(void)=0;
在圆圈和方形中:
void Draw(double radius)
如果你想要虚拟方法,参数必须匹配。
答案 2 :(得分:0)
Shape中的这个方法应该是(不需要空格)
class shape{
public:
virtual void Draw()=0;
};
当您声明Circle时,您需要Draw
方法(即没有半径位的方法)