如何在 Visual Studio 中使用多个文件时阻止重新定义类
How to stop class from being redefined when using multiple files in Visual Studio
我正在使用多个文件作为类定义和命名空间。包含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
不是那么可移植的(,始终属于每个头文件(每个头文件都有不同的宏名称(。否则,您将遇到更多问题。
相关文章:
- 定义C++新的环境变量并在 bat 文件中使用它
- 是否可以使用单个定义定义函数的常量和常规版本?(使用模板,自动,decltype等)
- 从使用概念定义的函数返回新对象
- 如何在C++中为 if 和 else 语句定义新行为
- 如何从 C++ 中的现有模板函数定义新函数
- 自定义分配器,包括放置新案例
- 正在通过const-ref未定义的行为捕获新构造的对象
- 如何在CPropertySheet中定义新颜色
- 谁定义新操作员
- 未定义的符号'fixed_address_empty_string':带有protobuf的新张量流运算
- 新的C ,未定义的参考
- boost :: fibonacci_heap:带有比较器重新定义圆形定义错误的嵌套定义
- 宏,用于定义带有添加前缀的新宏
- 取消脱壳:使用模板在多行类型定义中添加一个尖括号后的新行
- C 通过Typedef定义新类型
- 通过在此指针上放置新位置重新初始化对象时未定义的行为
- 在 ss.clear() 之后使用 ss.str( " ") 用于新定义的字符串流
- Eclipse CDT将方法定义定义到标头文件
- 是标头文件中使用“新”定义的成员指针泄漏
- LEX 程序中的未定义定义