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

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

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

我想这意味着我需要以某种方式阻止 math.cpp 或 main.cpp 再次包含 Vect.h,所以我尝试用 [=] 包围 Vect.h 文件16=]

    #ifndef VECT
    #define VECT
    //CODE
    #endif

然而这并没有奏效,现在我没主意了

在 Vect.h 中,我有 class 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);

math.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 是一个错误的名称,因为它可能与同名的标准 header 冲突,因此请尝试将其重命名为不同的名称。

包括你在问题开头显示的守卫(或者 #pragma once 不是那么便携)总是属于每个 header 文件(每个文件都有不同的宏名称) .否则你会遇到更多问题。