【发布时间】:2016-03-19 12:05:43
【问题描述】:
形状头文件
错误:“矩形”的构造函数必须显式初始化没有默认构造函数的基类“形状”
#ifndef Rectangle_hpp
#define Rectangle_hpp
#include "shape.hpp"
#include <stdio.h>
class Rectangle:public Shape{
double m_length;
double m_width;
public:
Rectangle(double length,double width):Shape("Rectangle"){}
double getPerimeter();
double getArea();
};
#endif /* Rectangle_hpp */
形状 cpp 文件
错误:重新定义“矩形”
#include "Rectangle.hpp"
#include "shape.hpp"
#include "Rectangle.hpp"
Rectangle::Rectangle(double length,double width):Shape("Rectangle"){
m_length = length;
m_width = width;
}
double Shape::getPerimeter(){
return 2;
}
double Shape::getArea(){
return 2;
}
BASE 类头文件
#ifndef shape_hpp
#define shape_hpp
#include <stdio.h>
class Shape{
const char* m_name;
public:
Shape(const char* name);
virtual double getPerimeter()=0;
virtual double getArea()=0;
char getType();
};
#endif /* shape_hpp */
基类cpp文件
#include "shape.hpp"
Shape::Shape(const char* name){
m_name = name;
}
char Shape::getType(){
return *m_name ;
}
我创建了另一个类“Circle”,其布局与 Rectangle 相同,但没有出现任何错误,这些错误只出现在矩形类中。我被卡住了,不知道为什么。
【问题讨论】:
-
Rectangle构造函数有两个定义 -
你也不需要在你的 rectangle.cpp 中使用 shape.hpp,因为你已经将它包含在了 rectangle.hpp 中。而且你有两次 rectangle.hpp。
标签: c++ inheritance polymorphism derived-class virtual-functions