类模板 - 找不到合适的运算符方法

class template - can't find appropriate operator method

本文关键字:运算符 方法 找不到      更新时间:2023-10-16

我正在尝试使用类模板和运算符重写在C++中实现自己的集合。

我的MySet.h文件中有以下代码:

#include "stdafx.h"
#pragma once
#include <iostream>
#include <string>
using namespace std;
#define DEFAULT_LEN 10
template <class T> class MySet
{
public:
    MySet(int len = DEFAULT_LEN)
    {
        elements = new T[len];
        count = 0;
    }
    ~MySet()
    {
        delete elements;
    }
    MySet<T> operator+(T &element)
    {
        cout << "Some code here!"; //deleted to simplify code, the problem is that this method is not seen in main
        return MySet<T>();
    }
    string writeSet()
    {
        string result = "";
        for (int i = 0;i < count; i++)
        {
            result += elements[i] + ", ";
        }
        return result;
    }
private:
    T* elements;
    int count;
};

我主要说的是:

#include "stdafx.h"
#include "MySet.h"
int main()
{
    MySet<int> a = MySet<int>(10);
    cout << a.writeSet();
    a = a + 2;
    a = a + 3;
    a = a + 4;
    cout << a.writeSet();
    return 0;
}

不幸的是,我在使用以下行进行编译时遇到了问题:

a = a + 2;

输出为:

1>c:pathmain.cpp(11): error C2679: binary '+': no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion)
1>  c:pathmyset.h(22): note: could be 'MySet<int> MySet<int>::operator +(T &)'
1>          with
1>          [
1>              T=int
1>          ]

这怎么可能?据我所知,由于T型,MySet<T> operator+(T &element)应该足够了。我错过了什么?

必须是:

MySet<T> operator+(const T &element)