如何在 c++ 中的模板中重载>>或<<
How to overload >> or << in Template in c++
我是C++的初学者。我正在尝试为我的模板重载我的 cout 运算符。但是,它不接受我用于类运算符的方式。所以,我在这里学习你的想法。
这是我的标题
#include <iostream>
using namespace std;
template <class T>
class Set{
private:
T *data;
int index;
public:
Set() :index(0){
data=new T[100];
}
void addElement(T t){
int x=0,i;
for(i=0;i<index;i++){ // to add element
if(data[i]==t){
cout<<"This element ("<<t<<") cannot be added since it is already in the elements"<<endl;
x=1;
}
}
if(x!=1)data[index++]=t;
}
ostream& operator<<(ostream& s,const Set<T1>& b){ //place in which i want to overload
s<<"Printed";
return s;
}
};
这是我的主要
#include <iostream>
#include<string.h>
using namespace std;
#include "Stack.h"
int main(){
Set<int> x1;
x1.addElement(4);
x1.addElement(7);
cout<<x1;
return 0;
}
您的问题与模板化的类无关。
您正在尝试将operator<<
实现为类的非静态成员,但这不适用于二进制流operator<<
,它需要是非成员。 作为类成员实现的二元运算符只能是其左侧参数中的类的成员,在本例中为std::ostream
,并且您的类不是std::ostream
类。 因此,运算符需要是一个自由函数(非成员(。
如果将二进制operator<<
标记为类中的friend
,它不仅可以访问类的private
成员,更重要的是,编译器会将运算符视为声明类的周围命名空间中的自由函数,这正是您所需要的, 例如:
template <class T>
class Set{
...
public:
...
// inlined implementation
friend ostream& operator<<(ostream& s, const Set& b){
...
return s;
}
};
或:
template <class T>
class Set{
...
// non-inlined implementation
friend ostream& operator<<(ostream& s, const Set& b);
};
template <class T>
ostream& operator<<(ostream& s, const Set<T>& b){
...
return s;
}
附带说明一下,您的addElement()
可能存在缓冲区溢出。 它应该看起来更像这样:
void addElement(const T& t){
for(int i = 0; i < index; ++i){
if (data[i] == t){
cout << "This element (" << t << ") cannot be added since it is already in the elements" << endl;
return;
}
}
if (index >= 100){
cout << "This element (" << t << ") cannot be added since the elements is full" << endl;
return;
}
data[index++] = t;
}
此外,您的类丢失:
- 析构函数,用于
delete[]
elements
数组。 - 复制构造函数和复制赋值运算符,用于在
Set
对象之间创建elements
数据的深层副本。 - (C++11 及更高版本(移动构造函数和移动赋值运算符,用于在对象之间移动数组。
根据 3/5/0 的规则。
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- EASTL矢量<向量<int>>连续的
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- C :对矢量进行排序&lt; struct&gt;(结构有2个整数)基于结构的整数之一
- 明确的专业化“ CheckIntmap&lt;&gt;”实例化
- 什么是模板&lt;&gt;inline bla bla
- 编辑C Qlist&lt; object*&gt; gt;QML代码和一些QML警告中的模型
- eigen :: llt&lt;eigen :: matrixxd&gt;具有不完整的类型
- 错误,包括&lt; ctype&gt;在原子上使用C 11
- std::vector<;uint8_t>;当C++11/14启用时,手动复制而不是调用memcpy
- 如何加入向量&lt; int&gt;到C 中的单个INT
- 是std :: set&lt; std :: future&gt;不可能存在
- 是numeric_limits&lt; int&gt; :: is_modulo从逻辑上矛盾
- opencv 2.4.7在iOS错误背景_segm.hpp #include&lt; list&gt;未找到
- 在修改列表后,std :: list&lt; t&gt; :: end()的值是否会更改
- ///<评论></评论>在Visual Studio中