【发布时间】:2019-03-21 00:18:35
【问题描述】:
我想声明全局变量,避免单例模式,像这样使用静态变量,没有封装。最终目标是能够从任何函数/对象(如全局变量)访问变量。代码无法在 main() 下的 vec.pushback 编译,这里需要帮助。代码有什么缺点吗?它可以在多线程环境中使用吗?谢谢。
struct Properties {
static int roll;
static std::string name;
static std::vector<std::string> vec;
};
int Properties::roll = 1;
std::string Properties::name{};
std::vector < std::string > vec;
int main()
{
Properties::roll = 1;
Properties::name = "Jack";
Properties::vec.push_back("Hellooooo"); // unresolved external symbol "public: static class
return 0;
}
【问题讨论】:
-
投票结束是一个错字。
std::vector < std::string > vec;应该是std::vector < std::string > Properties::vec; -
尽管上面有评论,但最终目标确实不清楚。
-
FWIW,如果你想要全局对象,它的作用域是一个名字,那么使用一个命名空间,而不是一个类/结构。
-
这些只是全局变量,具有相同的缺点。唯一的区别是,与在全局范围内声明它们相比,它们需要更多的输入。
-
@NathanOliver:命名空间似乎更好。
标签: c++