【发布时间】:2014-03-09 17:10:53
【问题描述】:
我正在学习 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)
【问题讨论】:
-
简而言之,
void Draw(void)与void Draw(double)不一样,所以你并没有覆盖基类的纯虚方法。那里有很多重复项。
标签: c++ class inheritance abstract