繁体   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