【问题标题】:c++ inheritance /redefinition errorc++继承/重定义错误
【发布时间】: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


【解决方案1】:
  1. 错误:“矩形”的构造函数必须显式初始化没有默认构造函数的基类“形状”

此错误不应该存在,并且它不在我的机器中(GCC 4.9.2)

  1. 错误:重新定义“矩形”

在你的 Rectangle.hpp 中,你已经定义了类 Rectangle 的构造函数,你只需要声明它

Rectangle(double length,double width)

【讨论】:

    【解决方案2】:

    在您的头文件中,您定义 Rectangle 构造函数,其主体为空 {}

    在您的 CPP 文件中,您再次定义 Rectangle 构造函数。它在抱怨重复。

    你的头文件应该只包含声明:

    Rectangle(double length, double width);
    

    【讨论】:

      猜你喜欢
      • 2020-02-06
      • 2021-05-01
      • 2011-09-17
      • 2015-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-21
      相关资源
      最近更新 更多