gpt4 book ai didi

c++ - 运算符重载类型转换错误

转载 作者:行者123 更新时间:2023-11-30 01:56:25 25 4
gpt4 key购买 nike

我有一个模板类,我需要重载运算符 ==。我通过以下方式执行此操作

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 是非常量(这意味着您可以修改迭代器,但不能修改它指向的东西)。

关于c++ - 运算符重载类型转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19773471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com