所以我有这个头文件:
#include <iostream>
#include <string>
class Furniture
{
float width, height, depth;
std::string name;
public:
// Constructor
Furniture(std::string name);
void ReadDimensions();
virtual void Print();
};
Run Code Online (Sandbox Code Playgroud)
这个 .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";
}
Run Code Online (Sandbox Code Playgroud)
当我尝试编译我的主文件时,它包含两个用它们自己的文件编写的子类,它给了我一个错误
“Furniture.h:4: 错误:重新定义‘class Furniture’
Furniture.h:5: 错误:'class Furniture' 的先前定义"
但据我所知,我正确地声明了这个类,并没有在定义中重新声明它。为什么它给我这个错误,我能做些什么来解决它?
尝试在您的 .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
Run Code Online (Sandbox Code Playgroud)