【问题标题】:"Error: Redefinition of Class" - But No Redeclaration“错误:重新定义类” - 但没有重新声明
【发布时间】:2016-02-17 18:14:34
【问题描述】:

所以我有这个头文件:

#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: 错误:重新定义‘类家具’

Furniture.h:5: 错误:‘类家具’的先前定义”

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

【问题讨论】:

  • 你在 cc 文件 main 中也有#include "Furniture.h" 吗?您是否在任何地方都包含了家具 cc 文件?
  • 我看不到 #pragma once 或在标题中包含警卫。

标签: c++


【解决方案1】:

尝试在您的 .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

【讨论】:

  • 我会跳过双下划线,例如names are reserved 用于实现。
  • 顺便说一句,你回答的主题叫做 include guards。
  • 非常感谢,我会确保我阅读了包含警卫。
猜你喜欢
  • 2013-02-25
  • 2012-01-29
  • 1970-01-01
  • 2023-04-02
  • 2014-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多