[英]error: no match for 'operator=' (operand types are 'std::map<int, double>::iterator
//a class used to make operations on Polynominal
class Polynominal
{
public:
map<int, double> monomial;//int is exp,double is coefficient
Polynominal();
~Polynominal();
Polynominal(const Polynominal& other);
/*...many functions*/
};
//copy constructor
Polynominal::Polynominal(const Polynominal& other)
{
map<int, double>::iterator iter;
/*Throw error here. If I replace it with
"map<int, double>tem=other.monomial;"
and then operate on tem, then it run well.*/
for(iter=other.monomial.begin();iter!=other.monomial.end();iter++)
monomial.insert(pair<int, double>(iter->first, iter->second));
}
In the process of using iterator, it throws an error. 在使用迭代器的过程中,它将引发错误。 If I replace it with
如果我替换为
map<int, double>tem=other.monomial;
and then operate on tem, then it run well. 然后在tem上运行,然后运行良好。 I know putting data in public is a bad habit, but now I just want to know why it throw this error.
我知道将数据公开是一个坏习惯,但是现在我只想知道为什么会引发此错误。 I am searching for a long time on net.
我正在网上搜索很长时间。 But no use.
但是没用。 Please help or try to give some ideas how to achieve this.
请帮助或尝试给出一些想法来实现这一目标。 Thanks in advance.
提前致谢。
Problem is other
is a const reference which making other.monomial
const as well so only version of std::map::begin()
that returns const iterator is available, but you try to assign it to regular iterator. 问题是
other
是一个const引用,它也使other.monomial
const成为可能,因此只有返回const迭代器的std::map::begin()
版本才可用,但是您尝试将其分配给常规迭代器。 Fix could be of changing your iterator type: 解决方法可能是更改迭代器类型:
map<int, double>::const_iterator iter;
but you better use auto
instead or even better for range loop: 但您最好改用
auto
代替,甚至更好地使用range循环:
for( const auto &p : other.monomial )
monomial.insert( p );
However it is not clear why you need to implement copy ctor manually at all, compiler generated will do what you need without any effort. 但是,目前尚不清楚为什么需要完全手动执行copy ctor,生成的编译器将完成您所需的一切而无需付出任何努力。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.