如何在 Visual Studio 中使用多个文件时阻止重新定义类

How to stop class from being redefined when using multiple files in Visual Studio

本文关键字:新定义 定义 文件 Studio Visual      更新时间:2023-10-16

我正在使用多个文件作为类定义和命名空间。包含main((函数的main.cpp文件需要使用其中一个类,就像我的"math.cpp"文件中的命名空间math一样,因此它们都包含 #include"Vect.h",它具有类的声明。但是,由于 main(( 也需要使用 math 命名空间,因此它 #include "math.cpp"。如果我尝试运行它,编译器告诉我我已经在 main.obj 中定义了类 Vect,错误代码LNK2005。

我认为这意味着我需要以某种方式阻止数学.cpp或主要.cpp再次包含 Vect.h,所以我尝试用 Vect.h 文件包围

#ifndef VECT
#define VECT
//CODE
#endif

但是这不起作用,现在我没有想法

在 Vect.h 中,我有类 Vect 的声明(它在 Vect.cpp 中定义(

#pragma once
class Vect {
private:
float x;
float y;
float z;
public:
Vect(float a, float b, float c);
//Some other functions..
};

Main 创建 2 个 Vect 对象,并使用 math 命名空间创建第三个

#include "Vect.h"
#include "math.cpp"
int main() {
Vect a(1, 2, 3);
Vect b(0.5, -1, 4);
Vect c = vct::subtract(a, b);

数学.cpp文件:

#include "Vect.h"
namespace vct {
Vect subtract(Vect a, Vect b) {
Vect output(0, 0, 0);
//function code
return output;
}
}

不要在其他文件中包含.cpp文件。

如果您的main.cpp需要您的math.cpp提供某些声明,请提供该声明的math.h,并将其包含在两者中:

#include "Vect.h"
namespace vct {
Vect subtract(Vect, Vect);
}

但请注意,math.h是一个不好的名字,因为它可能与同名的标准标头冲突,因此请尝试将其重命名为其他名称。

包括您在问题开头显示的守卫(或者#pragma once不是那么可移植的(,始终属于每个头文件(每个头文件都有不同的宏名称(。否则,您将遇到更多问题。