簡體   English   中英

運算符重載中的類型轉換錯誤

[英]error in type conversion in operator overloading

我有一個模板類,我需要重載operator ==。 我通過以下方式做到這一點

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

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

您正在嘗試將const_iterator轉換為iterator

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();

另請注意, thisBegin不是const ,如您的示例所示。 這是因為你做了這樣的事情:

++secondBegin;

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

  • 你的方法是const意味着你只能在this上調用const函數
  • 您將const引用傳遞給方法,因此您只能在其上調用const函數

所以,兩者

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

返回const迭代器。

你無法將其分配到非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功能)

順便說一句,您可以使用std::mismatch簡單地比較兩個向量

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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