有没有办法在单独的 .h 和 .cpp 文件中定义在命名空间中声明的函数

Is there a way to define functions declared in a namespace in a separate .h and .cpp file?

本文关键字:函数 定义 声明 命名空间 文件 单独 有没有 cpp      更新时间:2023-10-16

我对 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; }是有效的。