【问题标题】:no operator found which takes a left operand... (using a class template)未找到采用左操作数的运算符...(使用类模板)
【发布时间】:2015-06-03 23:35:03
【问题描述】:

我正在重载类模板的运算符,我收到错误:Error 1 error C2678: binary '>' : no operator found which take a left-hand operand of type 'const CSet '

CSet.h:

bool CSet<T>::operator>(const CSet<T>& mySet) const{

    bool flag = false;

    for (int i = 0; i < size; i++){
        for (int j = 0; j < mySet.size; j++){
            if (arr[i] == mySet[j]){
                flag = true;
                break;
            }
            if (j == mySet.size - 1 && flag == false)
                return false;
        }
    }
    return true;
}

void CSet<T>::operator+=(T& myVal){
    T* temp = new T[size + 1];
    for (int i = 0; i < size; i++){
        if (arr[i] == myVal){
            delete[] temp;
            return;
        }
    }
    for (int i = 0; i < size; i++)
        temp[i] = arr[i];
    delete[] arr;
    arr = temp;
    arr[size] = myVal;
}

mian.cpp:

#include "Set.h"


int main(){
    CSet<int> mySet, yourSet;
    mySet += 3; mySet += 4; mySet += 5;
    yourSet += 5; yourSet += 4; yourSet += 3;
    bool boom;
    boom = mySet == yourSet;
} 

现在,从错误中我了解到编译器无法将 T 转换为 int。 我的问题是:为什么不呢?这不是模板的全部目的吗?
一定有什么我错过了,因为这没有意义(至少对我来说)。

【问题讨论】:

  • 你是如何定义operator ==的?
  • @Alejandro 哦,我完全忘记了那个 xD。它只是检查两组是否相等。要我添加定义吗?
  • 虽然与您的问题无关,但您可能希望将T* temp = new T[size + 1]; 移动到operator += 中,直到第一个for 循环之后。如果您很快就不得不解除分配,为什么还要分配一个数组呢?或者,您可以使用 std::vectorstd::move 您的旧 vector 进入它,并获得 vector 的好处! :)
  • @Alejandro 有道理,谢谢你的建议。但是,就我喜欢向量而言,我不允许使用它们,因为这是家庭作业,我们有限制。

标签: c++ templates


【解决方案1】:

您很可能希望/需要将其更改为:

bool CSet<T>::operator>(const CSet<T>& mySet) const {
    // ...                                    ^^^^^ Note addition here.

当你像这样调用这个成员函数时:

if (x > y) ...

相当于:if (x.operator&gt;(y))。参数类型上的const 表示右操作数可以是const。要允许左操作数也为 const,请在上面显示的位置添加 const

【讨论】:

  • 现在我收到错误:错误 1 ​​错误 C2244: 'CSet::operator >' : 无法将函数定义与现有声明匹配。这是什么意思?
  • 您是否在头文件中添加了新的const 说明符?
  • 我做到了。而且,即使我希望左操作数是可修改的,是否还需要添加 const 说明符?
  • @JamesSonnino:声明和定义都需要const
  • @JerryCoffin 我做了,我编辑了这个问题。现在我收到一个错误,指出运算符 += 对于该类是非法的,并且“二进制 '+=' : 没有找到采用 'int' 类型的右手操作数的运算符(或者没有可接受的转换) ”。现在我没有对这个运算符使用 const,那么这里有什么问题?
猜你喜欢
  • 2018-10-12
  • 1970-01-01
  • 2022-01-19
  • 1970-01-01
  • 1970-01-01
  • 2014-05-02
  • 1970-01-01
  • 1970-01-01
  • 2019-07-31
相关资源
最近更新 更多