错误:与'operator='不匹配(操作数类型为"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是一个常量引用,它也使other.monomial常量,因此只有返回常量迭代器的std::map::begin()版本可用,但您尝试将其分配给常规迭代器。修复可能是更改迭代器类型:

  map<int, double>::const_iterator iter;

但是您最好使用auto而不是范围循环,甚至更好:

 for( const auto &p : other.monomial )
          monomial.insert( p );
但是,目前

尚不清楚为什么您需要手动实现复制ctor,生成的编译器将毫不费力地完成您需要的操作。

相关内容

最新更新