这个问题建立在这两个 stackoverflow 帖子的基础上:
问题是:为什么类/结构/枚举不会出现多重定义错误?为什么它只适用于函数或变量?
我写了一些示例代码来试图解决我的困惑。有 4 个文件:namespace.h、test.h、test.cpp 和 main.cpp。第一个文件包含在 test.cpp 和 main.cpp 中,如果取消注释正确的行,则会导致多重定义错误。
// namespace.h
#ifndef NAMESPACE_H
#define NAMESPACE_H
namespace NamespaceTest {
// 1. Function in namespace: must be declaration, not defintion
int test(); // GOOD
// int test() { // BAD
// return 5;
//}
// 2. Classes can live in header file with full implementation
// But if the function is defined outside of the struct, it causes compiler error
struct TestStruct {
int x; …Run Code Online (Sandbox Code Playgroud) 我试图在C++中对自定义结构的向量进行排序
struct Book{
public:int H,W,V,i;
};
Run Code Online (Sandbox Code Playgroud)
用一个简单的仿函数
class CompareHeight
{
public:
int operator() (Book lhs,Book rhs)
{
return lhs.H-rhs.H;
}
};
Run Code Online (Sandbox Code Playgroud)
在尝试时:
vector<Book> books(X);
.....
sort(books.begin(),books.end(), CompareHeight());
Run Code Online (Sandbox Code Playgroud)
它给我异常"无效的运算符<"
这个错误是什么意思?
谢谢
我相信这是一个简单的错误,因为每个其他文件都抱怨同样的错误.但我试图将这些辅助函数放在名为Tools的命名空间中,它怎么还能报告这个错误?整个项目可以在这里找到https://github.com/luming89/MyGameEngine.顺便说一句,如果你知道如何用glm替换这些助手,请告诉我.我真的很感激!
// This is the Tools.h file
#ifndef TOOLS_H
#define TOOLS_H
#define MATH_PI 3.1415926535897932384626433832795
#define ToRadians(x) (float)(((x) * MATH_PI / 180.0f))
#define ToDegrees(x) (float)(((x) * 180.0f / MATH_PI))
typedef glm::detail::tquat<float, glm::precision::highp> Quaternion;
namespace Tools
{
glm::mat4 initRotationFromVectors(const glm::vec3& n, const glm::vec3& v, const glm::vec3& u) // forward, up, right
{
glm::mat4 res; // Identity?
res[0][0] = u.x; res[1][0] = u.y; res[2][0] = u.z; res[3][0] = 0;
res[0][1] = v.x; res[1][1] = v.y; res[2][1] = v.z; res[3][1] = 0; …Run Code Online (Sandbox Code Playgroud) 我就是不明白为什么这不会编译。
我有三个文件:
主程序
#include "expression.h"
int main(int argc, char** argv)
{
return 0;
}
Run Code Online (Sandbox Code Playgroud)
表达式.h
#ifndef _EXPRESSION_H
#define _EXPRESSION_H
namespace OP
{
char getSymbol(const unsigned char& o)
{
return '-';
}
};
#endif /* _EXPRESSION_H */
Run Code Online (Sandbox Code Playgroud)
和表达式.cpp
#include "expression.h"
Run Code Online (Sandbox Code Playgroud)
(Ofc 里面还有更多内容,但即使我评论除了#includeout之外的所有内容,它也不起作用)
我编译它
g++ main.cpp expression.cpp -o main.exe
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误:
C:\Users\SCHIER~1\AppData\Local\Temp\ccNPDxb6.o:expression.cpp:(.text+0x0): multiple definition of `OP::getSymbol(unsigned char const&)'
C:\Users\SCHIER~1\AppData\Local\Temp\cc6W7Cpm.o:main.cpp:(.text+0x0): first defined here
collect2.exe: error: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)
问题是,它似乎解析expression.h了两次。如果我只是使用main.cppOR编译它,expression.cpp我就不会收到错误消息。编译器只是忽略我的 #ifndef 并继续......
有什么线索吗?