我想定义一个全局容器(C++03),这是我尝试过的示例代码,但它不起作用。
#include <vector>
#include <string>
using namespace std;
vector<string> Aries;
Aries.push_back("Taurus"); // line 6
int main() {}
编译错误:
prog.cpp:6:1: error: 'Aries' does not name a type
看来我可以定义一个空的全局向量,但无法填充它。看起来在 C++03 中,我也无法指定初始化程序,例如:
vector<string> Aries = { "Taurus" };
我在这里犯了一个错误吗?或者我该如何解决这个问题?
我尝试在 StackOverflow 上搜索,看看以前是否已经回答过这个问题,但只遇到了这些帖子:C++ 中的全局对象 https://stackoverflow.com/questions/4395102/global-objects-in-c, 在C++中定义全局常量 https://stackoverflow.com/questions/2268749/defining-global-constant-in-c,这无助于回答这个问题。
我找到了一个巧妙的解决方法来“初始化”C++03 全局 STL 容器(实际上是在之前“全局”执行代码)main()
)。这使用了逗号运算符。参见示例:
#include <vector>
#include <string>
#include <iostream>
using namespace std;
vector<string> Aries;
// dummy variable initialization to setup the vector.
// using comma operator here to cause code execution in global scope.
int dummy = (Aries.push_back("Taurus"), Aries.push_back("Leo"), 0);
int main() {
cout << Aries.at(0) << endl;
cout << Aries.at(1) << endl;
}
Output
Taurus
Leo
唯一真正的问题(如果可以这么说的话)是额外的全局变量。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)