【发布时间】:2016-07-26 21:39:51
【问题描述】:
我不确定这是否是我的 C++ 语法错误,还是根本无法完成。
我想定义一个将 std::map 作为构造函数参数的类。然后我想通过传递一个“临时”(适合称之为“右值”?)std::map 来创建该类的一个实例。 IE。我不想创建一个左值 std::map 然后将其传递给构造函数。
这可以实现吗?我尝试了以下方法(注释行显示尝试失败)
#include <map>
#include <string>
#include <iostream>
class Test
{
public:
Test(std::map<int,char>& rMap)
{
std::map<int,char>::iterator iter;
for (iter = rMap.begin(); iter != rMap.end(); ++iter)
{
mMap[iter->first] = mMap[iter->second];
}
}
virtual ~Test(){}
protected:
std::map<int, char> mMap;
};
int main()
{
std::cout << "Hello world!" << std::endl;
//Test test({1,'a'}); // Compile error.
//Test test(std::map<int,char>(1,'a')); // Also compile error.
//Test test(std::map<int,char>{1,'a'}); // Yet again compile error.
return 0;
}
这是我的编译器:
g++ (GCC) 4.4.7 20120313 (Red Hat 4.4.7-11)
编译错误可以根据要求发布,但我不确定如果我的问题是句法,它们是否有用。
谢谢。
【问题讨论】:
-
你试过
Test test(std::map<int, char>{{1, 'a'}});用两组大括号吗? -
@TimStraubinger - 根据您的建议尝试了此操作,但导致另一个编译错误。
-
什么“编译错误”?
-
使用引用 const 的构造函数更新了问题,并且还添加了我创建测试的三次失败尝试中的每一次的编译错误。
-
请注意,所有编译错误都指向同一行。这些错误与右值无关 - 您正在尝试将 const 迭代器分配给非 const 迭代器。
标签: c++ dictionary std stdmap rvalue