//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
是一个常量引用,它也使other.monomial
常量,因此只有返回常量迭代器的std::map::begin()
版本可用,但您尝试将其分配给常规迭代器。修复可能是更改迭代器类型:
map<int, double>::const_iterator iter;
但是您最好使用auto
而不是范围循环,甚至更好:
for( const auto &p : other.monomial )
monomial.insert( p );
但是,目前尚不清楚为什么您需要手动实现复制ctor,生成的编译器将毫不费力地完成您需要的操作。