我正在为类定义和命名空间使用多个文件。包含 main() 函数的 main.cpp 文件需要使用其中一个类,就像我的“math.cpp”文件中的命名空间数学一样,因此它们都包含#include“Vect.h”,它具有类的声明。但是,由于 main() 还需要使用数学命名空间,因此它具有#include "math.cpp"。如果我尝试运行它,编译器会告诉我我已经在 main.obj 中定义了类 Vect,错误代码为 LNK2005。
我假设这意味着我需要停止 math.cpp 或 main.cpp 以某种方式再次包含 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);
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 冲突,因此请尝试将其重命名为不同的名称。
包括像您在问题开头显示的 guard (或者 #pragma once
不是那么便携)总是属于每个头文件(每个头文件都有不同的宏名称)。否则你会遇到更多问题。
关于c++ - 在 Visual Studio 中使用多个文件时如何阻止类被重新定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57842531/