c++简单程序实现中的继承和虚函数错误

C++ Inheritance and Virtual function error in simple program implementation

本文关键字:函数 错误 继承 简单 程序 实现 c++      更新时间:2023-10-16

我正在学习c++,我正在尝试实现一个简单的c++程序来创建一个抽象类,如下所示:请解释为什么我得到这个错误后编译?请用简单的语言解释一下,我不是专业术语专家,还在学习面向对象编程概念。提前感谢(代码和错误如下)

代码:

/*
 * 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)

问题如下:在shape类中,您声明draw为不带参数:

virtual void Draw(void)=0;

而子类circlesquaredraw期望双精度:

void Draw(double radius)

circle中,我认为radius(连同可能像center这样的东西)应该传递给构造函数,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类也有同样的问题

Draw方法的参数不匹配

形状的

:

virtual void Draw(void)=0;

在圆形和方形中:

void Draw(double radius)

如果你想使用虚方法,参数必须匹配

Shape中的方法应该是(不需要void)

class shape{ 
public: 
    virtual void Draw()=0;
};

当你声明Circle时,你需要一个Draw方法(即没有半径位的方法)