外部常量,未命名的命名空间



我有一个项目需要"使用未命名的命名空间创建一个常量变量",我需要与另一个.cpp文件中的函数共享它。它说变量声明可以在他们自己的文件中。提到了 extern 关键字的使用,我想出了如何使用 extern,将 var 放在头文件中并声明为 like extern const char varname;,在我的 main.cpp 中为其分配一个值(const char varname = A;全局高于 main 函数),并能够在另一个.cpp文件中使用它。但我不确定如何使用未命名的命名空间。在示例文件中,它们在主文件中具有以下内容:

namespace
{
  extern const double time = 2.0;
}

但是现在有如何在另一个.cpp文件中访问它的示例。我尝试用我的变量这样做,但在另一个文件中出现错误,我尝试使用它说它没有在该范围内声明。

有人可以提供一些关于我应该在这里做什么来利用这两件事的见解吗?

您可以尝试编写一个访问器函数,如下所示:

主.cpp

#include "other.hpp"
namespace
{
    const double time = 2.0;
}
int main()
{
    tellTime();
    return 0;
}
const double getTime()
{
    return time;
}

其他.hpp

#ifndef OTHER_HPP_INCLUDED
#define OTHER_HPP_INCLUDED
const double getTime();
void tellTime();
#endif // OTHER_HPP_INCLUDED

其他.cpp

#include <iostream>
#include "other.hpp"
void tellTime()
{
    std::cout << "Time from the anonymous namespace of main.cpp is " << getTime() << std::endl;
}

我认为任何数量的外部实习都无济于事:https://stackoverflow.com/a/35290352/1356754

您可以通过对变量的其他引用来访问它。

例如:

namespace
{
  const double time = 2.0;
  const double & local_ref_time(time); //Create a local referece to be used in this module
}

extern const double & global_ref_time(local_ref_time); //Create the global reference to be use from any other modules

最新更新