#include<iostream>
using namespace std;
template<class T>
class A
{
private:
T value;
public:
A(){this->value=0;}
A(T value)
{
this->value=value;
}
~A(){}
T getA();
//定义友元函数 实现运算符+的重载
template<class T1>
friend A<T1>& operator+(A<T1> &a,T1 value);
//非友元函数
A& operator-(T value)
{
this->value-=value;
return *this;
}
//前置++,没有参数int,可以作为左值,故要返回引用类型
A& operator++()
{
this->value+=1;
return *this;
}
//后置++,有参数int,不能作为左值,不需要返回引用类型
A operator++(int)
{
A old=*this;
++(*this);
return old;
}
//赋值
A& operator=(const A& b)
{
if(this==&b)return *this;
value=b.value;
return *this;
}
//重载<<或者>>运算符不能类内定义,类外实现
friend ostream& operator<<(ostream&out,const A<T>& a)
{
out<<a.value;
return out;
}
friend istream& operator>>(istream& in,A<T>& a)
{
in>>a.value;
return in;
}
};
template<class T>
T A<T>::getA()
{
return value;
}
template<class T>
A<T>& operator+(A<T> &a,T value)
{
a.value+=value;
return a;
}
int main()
{
//测试如下:
A<int> a(5);
a=a+2;
A<int> b=a++;
cout<<b<<endl;;
A<int> c;
cin>>c;
cout<<c<<endl;
c=c-1;
cout<<c<<endl;
return 0;
}
C++类模板 实现运算符重载
最新推荐文章于 2026-05-02 16:00:52 发布
本文详细介绍了C++中模板类的使用方法,并通过具体实例展示了如何在模板类中重载运算符,包括加法、减法、前置和后置自增运算符等。同时,还讲解了友元函数的定义和使用,以及重载输入输出流运算符的外部实现。

1982

被折叠的 条评论
为什么被折叠?



