gpt4 book ai didi

c++ - 外部常量,未命名的命名空间

转载 作者:搜寻专家 更新时间:2023-10-31 02:13:07 26 4
gpt4 key购买 nike

我有一个项目需要“使用未命名的命名空间创建常量变量”,我需要与另一个 .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 文件中访问它。我尝试用我的变量这样做,但在另一个文件中出现错误,我尝试使用它说它没有在该范围内声明。

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

最佳答案

您可以尝试像这样编写访问器函数:

main.cpp

#include "other.hpp"

namespace
{
const double time = 2.0;
}

int main()
{
tellTime();
return 0;
}

const double getTime()
{
return time;
}

other.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;
}

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

关于c++ - 外部常量,未命名的命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41815309/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com