【发布时间】:2019-07-04 19:55:52
【问题描述】:
我是编程新手,在我的作业中,任务是交换不同复制地图中的第二个元素,如果我在复制版本中更改某些内容,原始地图也会更改,但我没有知道怎么写copy函数。
template <class T, class P>
class map_swapper
{
public:
map_swapper(map <T, P>& Cmap)
{
map<T, P> & copym(Cmap);
}
void swap(const T &t1, const T &t2) // I don't know if this function here is good or not because of the undeclared identifier error I can't get here, it is just a guess.
{
P a;
a = copym[t1];
copym[t1] = copym[t2];
copym[t2] = a;
}
};
int main()
{
std::map<int, std::string> mapS1;
map_swapper<int, std::string> mapS2(mapS1);
mapS1[0] = "zero";
mapS1[1] = "one";
mapS1[2] = "two";
std::map<int, int> mapI1;
map_swapper<int, int> mapI2(mapI1);
mapI1[0] = 0;
mapI1[1] = 1;
mapI1[2] = 2;
mapS2.swap(0, 2);
mapI2.swap(0, 1);
for (typename std::map <int, std::string> ::iterator it = mapS1.begin(); it != mapS1.end(); it++)
{
std::cout << it->first << " ";
std::cout << it->second << std::endl;
}
for (typename std::map <int, int> ::iterator it = mapI1.begin(); it != mapI1.end(); it++)
{
std::cout << it->first << " ";
std::cout << it->second << std::endl;
}
return 0;
}
我得到Error C2065 'copym': undeclared identifier,因为我在构造函数中声明了“copym”,但不知道如何从那里提取声明并将构造函数仅用于赋值。
输出应该是这样的:
0 two
1 one
2 zero
0 1
1 0
2 2
【问题讨论】:
-
我们听说你必须写一个类
map_swapper?因为这是一种复杂而奇怪的做事方式。只写一个函数来做交换,而不是写一个类。 -
要回答您的具体问题,请将
copym移出构造函数并将其作为私有成员放入类中。因为它是一个引用,所以您必须使用初始化列表来绑定它,所以不能分配给引用(分配给引用总是分配给引用绑定的对象,而不是引用本身)。 -
是的,他们告诉我们使用一个类来让它变得有点复杂
标签: c++ class constructor copy