如何覆盖>&燃气轮机;C+中模板类的运算符+;? 在谷歌搜索了无数小时之后,我无法找到如何在C++中重写模板类的输入操作符。我已经找到了关于如何重写常规类的运算符以及如何重写输出运算符的答案。试图把我从中学到的东西结合起来,结果一无所获
到目前为止,我编写的代码是: 类的头文件:如何覆盖>&燃气轮机;C+中模板类的运算符+;? 在谷歌搜索了无数小时之后,我无法找到如何在C++中重写模板类的输入操作符。我已经找到了关于如何重写常规类的运算符以及如何重写输出运算符的答案。试图把我从中学到的东西结合起来,结果一无所获,c++,templates,overriding,operators,C++,Templates,Overriding,Operators,到目前为止,我编写的代码是: 类的头文件: #include <iostream> template <class T> class Set { private: T **array; int max; public: Set(); Set(int); ~Set(); int Max() { return max; }; friend std::ifstream& opera
#include <iostream>
template <class T>
class Set
{
private:
T **array;
int max;
public:
Set();
Set(int);
~Set();
int Max()
{
return max;
};
friend std::ifstream& operator>> (std::ifstream &input, Set<T> &obj)
{
for (int i = 0; i < obj->max; i++)
{
T a;
input >> a;
obj.array[i] = new T;
obj.array[i] = a;
}
return input;
};
};
template <class T>
Set<T>::Set()
{
max = 0;
array = new T *[max];
}
template <class T>
Set<T>::Set(int a)
{
max = a;
array = new T *[max];
}
template <class T>
Set<T>::~Set()
{
delete[] array;
}
#包括
模板
类集
{
私人:
T**阵列;
int max;
公众:
Set();
Set(int);
~Set();
int Max()
{
返回最大值;
};
friend std::ifstream&operator>>(std::ifstream&input,Set&obj)
{
对于(int i=0;imax;i++)
{
Tα;
输入>>a;
对象数组[i]=新的T;
对象数组[i]=a;
}
返回输入;
};
};
模板
Set::Set()
{
max=0;
数组=新的T*[max];
}
模板
Set::Set(int a)
{
max=a;
数组=新的T*[max];
}
模板
Set::~Set()
{
删除[]数组;
}
主程序:
#include "set.hpp"
int main(){
Set<float> obj;
std::cin >> obj;
return 0;
}
#包括“set.hpp”
int main(){
设置obj;
标准:cin>>obj;
返回0;
}
在尝试编译时,我遇到以下两个错误:
no match for 'operator>>' (operand types are 'std::istream' {aka 'std::basic_istream<char>'} and 'Set<float>')
no operator ">>" matches these operands -- operand types are: std::istream >> Set<float>
与“operator>>”不匹配(操作数类型为'std::istream'{aka'std::basic_istream'}和'Set')
没有运算符“>>”与这些操作数匹配--操作数类型为:std::istream>>集
如果这很重要,我会使用gcc编译器。
谢谢大家! 您可以像这样过载:
模板
类集
{
...
模板
friend std::istream&operator>>(std::istream&input,Set&obj);
};
模板
std::istream&operator>>(std::istream&input,Set&obj)
{
...
返回输入;
}
或
您可以在类中定义它,如:
模板
类集
{
...
friend std::istream&operator>>(std::istream&input,Set&obj)
{
返回输入
}
}
在第一个示例中,您声明my friendoperator>
实例化是集合
模板类
的一个实例化的朋友。在第二个示例中,我们内联了friend函数,只允许friend操作符>
的一个实例化成为集合的一个实例化的朋友
这里有一个更好的答案,与操作符obj.array[i]=newt有关;对象数组[i]=a代码>不编译。应该是*obj.array[i]=a代码>。另一个“打字错误”:std::ifstream
!=<代码>标准::istream
(无f
)std::cin
不是前者,而是后者。析构函数忘记删除数组的元素。使用std::vector
作为成员可能会解决很多问题。这是我第一次在谷歌上搜索的最佳结果,它显示了如何做的代码示例。我感觉你们对自己无数个小时的搜索并不完全诚实。谢谢你们,我们被要求解决这个问题是使用数组,而不是向量。我会修正打字错误,因为某些原因我一直在写ifstream而不是istream。。。我和我的朋友都偶然发现了这个相关的问题,但我们无法完全实施/理解提议的解决方案。我确实将操作符函数移到了头文件中,正如在那个问题中所建议的那样。我将研究更多的模板,希望我能获得所需的知识。再次感谢你!我更喜欢OP的版本(有固定的打字错误),函数不是模板(允许匹配派生类,如果有的话,并就地构建)。只有具有正确功能的朋友(您的操作员>
有权访问集合
)。