![](/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.