“错误:重新定义类” - 但没有重新声明

时间:2016-02-17 18:14:34

标签: c++

所以我有这个头文件:

#include <iostream>
#include <string>

class Furniture
{
    float width, height, depth;
    std::string name;

public:
    // Constructor
    Furniture(std::string name);
    void ReadDimensions();
    virtual void Print();
};

这个.cc文件用于定义上面声明的函数:

#include "Furniture.h"

Furniture::Furniture(std::string name)
{
    this->name = name;
}

void Furniture::ReadDimensions()
{
    // Read width
    std::cout << "Enter width: ";
    std::cin >> width;
    // Read height
    std::cout << "Enter height: ";
    std::cin >> height;
    // Read depth
    std::cout << "Enter depth: ";
    std::cin >> depth;

    if (width <= 0 || height <= 0 || depth <=0)
            std::cout << "You entered invalidd values\n";
}

当我尝试编译包含两个用自己的文件编写的子类的主文件时,它给出了一个错误,其中包含

“Furniture.h:4:错误:重新定义'class Furniture'

Furniture.h:5:错误:'class Furniture'的先前定义“

但据我所知,我正确地宣布了这个类,并没有在定义中重新声明它。为什么它会给我这个错误,我该怎么做才能解决它?

1 个答案:

答案 0 :(得分:4)

尝试在.h文件中添加以下代码。这将阻止重新定义。

#ifndef __FURNITURE_H__
#define __FURNITURE_H__

#include <iostream>
#include <string>

class Furniture
{
    float width, height, depth;
    std::string name;

public:
    // Constructor
    Furniture(std::string name);
    void ReadDimensions();
    virtual void Print();
};

#endif