类模板 - 找不到合适的运算符方法
class template - can't find appropriate operator method
我正在尝试使用类模板和运算符重写在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)
相关文章:
- 有没有一种方法可以通过"typedef"为重新定义的基本类型定义特征和强制转换运算符
- C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?
- 使用类型id运算符的最佳替代方法
- C++运算符 - 方法
- "operator()"在重载运算符方法中是什么意思,在priority_queue(STL)中用作C++中的比较器?
- 一种优雅或至少可行的方法,用于使用和接受具有重载方法和运算符的不同大小的文字数组常量
- 类方法的C++插入运算符
- 将方法委托给成员的重写运算符>
- 矢量擦除方法是否需要类才能具有 = 运算符?
- 使用新运算符C++创建多维数组的简单方法
- std::is_invocable 用于测试任意方法是否存在的语法(不仅是运算符())
- 使输出流式处理运算符适用于 boost::variant<std::vector<int>、int、double 的正确方法是什么>
- 运算符方法和返回对象"out-of-scope"?
- “A a = A()”有效吗?下面调用了哪些运算符/方法
- 在其赋值运算符方法中调用对象的析构函数
- 运算符方法会占用c++对象中的内存吗
- std::bad_alloc C++调用运算符 = 方法时引发的异常
- 在模板类中重载友元运算符方法
- 类模板 - 找不到合适的运算符方法
- 显式调用类的强制转换运算符方法是否比强制转换更好?