如何在 c++ 中的模板中重载>>或<<

How to overload >> or << in Template in c++

本文关键字:lt gt 重载 c++      更新时间:2023-10-16

我是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 的规则。