有没有办法在单独的 .h 和 .cpp 文件中定义在命名空间中声明的函数
Is there a way to define functions declared in a namespace in a separate .h and .cpp file?
我对 c++ 的许多领域仍然有点陌生,一个是通用.cpp和 .h 文件组织。
我正在创建一个包含一些结构和函数的命名空间。我想在类似于这个的 .h 文件中声明命名空间
//objectname.h
namespace ObjectName
{
Object Function(arguments);
}
函数中的声明.h
//function.h
//includes declarations used in the function definition as well
//as possibly a redundant function declaration.
Object Function(arguments);
然后是函数中的定义.cpp
//function.cpp
#include "Function.h"
Object Function(arguments)
{
....
}
这样您就可以抽象地查看objectname.h
中的命名空间,function.h
中的函数特定声明和function.cpp.
中的函数定义 一如既往,任何建议都非常感谢。(也基于Windows的C ++)
这
很好
//objectname.h
namespace ObjectName
{
Object Function(arguments);
}
你根本不需要 function.h。 如果要将命名空间拆分为多个文件,可以执行以下操作:
//function.h
//includes declarations used in the function definition as well
//as possibly a redundant function declaration.
namespace ObjectName
{
Object Function(arguments);
}
换句话说,您需要再次将声明包装在命名空间中。 (这是一个高级主题。 我不会这样做。
函数.cpp只需要说出它定义了哪个函数:
//function.cpp
#include "ObjectName.h"
Object ObjectName::Function(arguments)
{
....
}
请注意,使用头文件的语句是 #include
,而不是using
这不是它的工作原理:你的 function.h 在全局命名空间中定义了另一个Function
。拥有两个同名的函数正是命名空间的用途 - 库写入无需担心任何其他库中是否已经有Function
。
由于您的.cpp只定义了两个Function
中的一个,因此另一个是未定义的,并且在调用时会给出链接错误。
请注意,您不需要一次"定义"所有命名空间。以namespace std
为例,其内容可在例如 <vector>
,<list>
和<iostream>
。这是可能的,因为与类不同,命名空间可以重新打开。 namespace N { int x; } namespace N { int y; }
是有效的。
相关文章:
- 不同翻译单元中不可重载的非内联函数定义
- Visual Studio中的函数声明和函数定义问题
- 编写代码时C++出现错误:错误 1 错误 C2601:'circle':本地函数定义是非法的
- 具有enable_if外部类原型的模板类构造函数定义
- 类的前向声明之后的类成员函数定义,在类声明之前
- 为函数定义符号不明确的指针参数
- C++模板专用化 - 无法匹配函数定义
- 错误:在第 6 行'{'标记之前,此处不允许使用函数定义
- 找不到 #define 的函数定义
- 根据类型特征更改函数定义?
- 将抽象基类中的所有纯虚函数定义为 varaidaic 模板
- 命名空间更改函数定义
- "Type&"与C++函数定义中的"Type*"
- C++:为什么允许在另一个函数中声明函数,而不允许在函数定义中声明?
- 如何从 C++ 中的现有模板函数定义新函数
- 私有在函数定义/实现的返回值范围内是什么意思 (c++)?
- 越界成员函数定义是否需要一个完全限定的类名,直到全局范围
- 为什么c++允许成员函数定义中实例的私有成员访问
- Qt基类函数定义
- C++函数定义中参数列表后面额外一对括号的含义