【问题标题】:Class Type Redefinition C++类类型重定义 C++
【发布时间】:2014-04-10 00:46:45
【问题描述】:

我以前见过其他人问过这个问题,但他们收到的答案是他们的程序所独有的,很遗憾对我没有帮助。

首先,我有一个形状类 - 分为 .h 和 .cpp 文件

//Shape.h

    #include <string>
using namespace std;

class Shape
{
private:
    string mColor;

public:
    Shape(const string& color); // constructor that sets the color instance value
    string getColor() const; // a const member function that returns the obj's color val
    virtual double area() const = 0;
    virtual string toString() const = 0;
};

//Shape.cpp

#include "Shape.h"
using namespace std;

Shape::Shape(const string& color) : mColor(NULL) {
    mColor = color;
}
string Shape::getColor() const
{
    return mColor;
}

我的 Shape.h 类中不断出现错误,显示“Shape”:“class”类型重新定义。 知道为什么我可能会收到此错误吗?

【问题讨论】:

  • 它是否也指定了行?如果是这样,会发生什么?
  • Shape.h 有包含保护吗?
  • 它指定第 6 行恰好是 Shape 类之后的左括号。而且我没有包含保护 - 我不确定那是什么?
  • 题外话:修改你的getColor方法为: const string& getColor() const { return mColor;返回字符串的副本不是最优的。
  • 不要使用#pragma once。这是非标准的。使用#ifndef SHAPE_H...

标签: c++ redefinition


【解决方案1】:

include guard 添加到您的头文件中

#ifndef SHAPE_H
#define SHAPE_H

// put your class declaration here

#endif

而且你初始化成员 mColor 的方式不正确。您不能将 NULL 分配给字符串类型

Shape::Shape(const string& color) : mColor(color) {
}

将虚拟析构函数添加到 Shape 类,因为它用作具有虚函数的基础。

另外,不要在头文件中使用 using 指令。

【讨论】:

    【解决方案2】:

    这里好像要写一个抽象基类,但是这里有没有你编译但没有显示的其他文件?


    您必须再包含两次“shape.h”。 只需使用宏来防止这种情况。

    PS:我猜Rectangle是Square的基类,也是继承了Shape。

    【讨论】:

    • 其实有。我使用 Square、Rectangle、Circle 等类。
    猜你喜欢
    • 2019-12-14
    • 1970-01-01
    • 2016-09-27
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    • 1970-01-01
    • 2021-03-01
    • 1970-01-01
    相关资源
    最近更新 更多