![](/img/trans.png)
[英]error: no match for ‘operator<<’ (operand types are ‘std::ostream’ {aka ‘std::basic_ostream<char>’} and ‘std::_List_iterator<int>’)
[英]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));
}
在使用迭代器的过程中,它将引发错误。 如果我替换为
map<int, double>tem=other.monomial;
然后在tem上运行,然后运行良好。 我知道将数据公开是一个坏习惯,但是现在我只想知道为什么会引发此错误。 我正在网上搜索很长时间。 但是没用。 请帮助或尝试给出一些想法来实现这一目标。 提前致谢。
问题是other
是一个const引用,它也使other.monomial
const成为可能,因此只有返回const迭代器的std::map::begin()
版本才可用,但是您尝试将其分配给常规迭代器。 解决方法可能是更改迭代器类型:
map<int, double>::const_iterator iter;
但您最好改用auto
代替,甚至更好地使用range循环:
for( const auto &p : other.monomial )
monomial.insert( p );
但是,目前尚不清楚为什么需要完全手动执行copy ctor,生成的编译器将完成您所需的一切而无需付出任何努力。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.