2013-11-04 63 views
0

我有一個模板類,我需要重載運算符==。我在下面的方式做到這一點運算符重載中的類型轉換錯誤

template <typename T> 
class Polynomial { 
    vector<T> coefficients; 

    public: 
    Polynomial(vector<T> c); 

    bool operator ==(const Polynomial& second) const { 
      const typename vector<T>::iterator thisBegin = this->coefficients.begin(); 
      const typename vector<T>::iterator secondBegin = second.coefficients.begin(); 
      for (; ((thisBegin != this->coefficients.end()) && 
            (secondBegin != second.coefficients.end())); 
          ++thisBegin, ++secondBegin) { 
        if (*thisBegin != *secondBegin) 
          return false; 
      } 
      while (thisBegin != this->coefficients.end()) { 
        if (*thisBegin != 0) 
          return false; 
        ++thisBegin; 
      } 
      while (secondBegin != second.coefficients.end()) { 
        if (*secondBegin != 0) 
          return false; 
        ++secondBegin; 
      } 
      return true; 
    } 
}; 

然而,當我創建這個類T = INT的兩個對象,並嘗試應用此運營商

Polynomial<int> first(firstVector); 
Polynomial<int> second(secondVector); 
std::cout << (first == second) << std::endl; 

我得到了錯誤

problem2.cpp: In instantiation of ‘bool Polynomial<T>::operator==(const Polynomial<T>&) const [with T = int; Polynomial<T> = Polynomial<int>]’: 
problem2.cpp:63:32: required from here 
problem2.cpp:23:83: error: conversion from ‘std::vector<int, std::allocator<int> >::const_iterator {aka __gnu_cxx::__normal_iterator<const int*, std::vector<int, std::allocator<int> > >}’ to non-scalar type ‘std::vector<int, std::allocator<int> >::iterator {aka __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >}’ requested 

有人可以指出這種轉換有什麼問題嗎?謝謝!

回答

2

您正在嘗試轉換const_iteratoriterator

const typename vector<T>::iterator thisBegin = this->coefficients.begin(); 

this就是在這種背景下const,所以this->coefficients.begin();返回const_iterator。試試這個:也

typename vector<T>::const_iterator thisBegin = this->coefficients.begin(); 

注意thisBeginconst,因爲在你的榜樣。這是因爲你然後做這樣的事情:

++secondBegin; 

這就要求const_iterator是非const的(這意味着你可以修改迭代器,而不是它指向的東西)。

1
  • 你的方法是const意味着你只能呼籲this
  • 你傳遞const參考方法const功能,所以你只能調用const功能上它

所以,無論是

this->coefficients.begin(); 
second.coefficients.begin() 

返回常量迭代器。

您不能將它們分配到非const

有一個解決方案:

vector<T>::const_iterator& thisBegin = this->coefficients.begin(); 
vector<T>::const_iterator& secondBegin = second.coefficients.begin(); 

(使用引用const_iterator

甚至更​​好:

auto& thisBegin = this->coefficients.begin(); 
auto& secondBegin = second.coefficients.begin(); 

(到auto使用的引用,C++ 11功能)

順便說一句,你可以簡單地使用0123比較兩個向量

+0

您的示例爲您留下懸掛引用。 – juanchopanza

+0

@juanchopanza哎呀!哪裏? =) – Drop

+0

'vector :: const_iterator&thisBegin = this-> coefficients.begin();'和其他。 – juanchopanza