工厂设计模式中的纯虚函数错误

Cel*_*ery 3 c++ polymorphism inheritance abstract-class pure-virtual

学习期末考试并决定构建一个使用纯虚函数和多态性的程序。我陷入了一个非常奇怪的错误,也许我错过了一些东西。

这是 Shape 抽象类

#ifndef Shape_hpp
#define Shape_hpp

#include <stdio.h>
#include <string.h>

class Shape{
    const char* name;
public:
    Shape(const char* abc);
    virtual double getPerimeter()=0;
    virtual double getArea()=0;
};

#endif /* Shape_hpp */
Run Code Online (Sandbox Code Playgroud)

Shape .cpp 实现文件

#include "Shape.hpp"

Shape::Shape(const char *shape){
    name = shape;
}
Run Code Online (Sandbox Code Playgroud)

圆头文件

#ifndef Circle_hpp
#define Circle_hpp

#include "Shape.hpp"
#include <stdio.h>

class Circle:public Shape{
    double m_radius;
public:
    Circle(double rad);
    double getRadius();            
};

#endif /* Circle_hpp */
Run Code Online (Sandbox Code Playgroud)

圆.cpp实现文件

#include "Circle.hpp"
#include "Shape.hpp"

Circle::Circle(double rad):Shape("Circle"){
    m_radius = rad;
}

double Circle::getRadius(){
    return m_radius;
}

double Circle::getPerimeter(){
    return (2 * 3.14 * m_radius);
}

double getArea(){
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

我在抽象的“形状”类中声明了两个纯虚函数,并在圆头文件中访问了形状类的公共,如果我在圆类中声明纯虚函数,它将使其成为抽象的......错误说“ “getPerimeter”的外部定义与“Circle”中的任何声明都不匹配”

我是不是错过了什么,还是我想错了。。

帮助将不胜感激。谢谢!

Joh*_*nck 5

您需要声明您定义的所有成员函数。所以在class Circle你需要添加:

virtual double getPerimeter();
Run Code Online (Sandbox Code Playgroud)

或者在 C++11 中更好:

double getPerimeter() override;
Run Code Online (Sandbox Code Playgroud)