簡體   English   中英

錯誤:“ operator =”不匹配(操作數類型為“ std :: map” <int, double> ::迭代器

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM