没有找到接受左操作数的操作符…(使用类模板)

no operator found which takes a left operand... (using a class template)

本文关键字:操作符 操作数      更新时间:2023-10-16

我正在重载类模板的操作符,我得到了错误:错误1错误C2678: binary '>':没有找到左操作数类型为'const CSet &lt的操作符;int>的

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。我的问题是:为什么不呢?这不就是模板的全部目的吗?
一定有什么东西我错过了,因为这没有意义(至少对我来说)。

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

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

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

if (x > y) ...

等于:if (x.operator>(y))。参数类型中的"const"表示右操作数可以为const。要允许左操作数为const,您可以在上面所示的位置添加const