C++重载操作符

重载的函数操作符,对对象使用起来就像对象是一个函数一样

class A
{
public:
A(int n);
int operator()(int n);  //需要一个参数,返回int类型
void output();
int x;
};
A::A(int n):x(n)
{
}
int A::operator()(int n)
{
x=n;           //实现.就是令数据成员x等于参数n
return x;
}
void A::output()
{
cout<<x<<endl;
}

int main()
{
A a(3);
a.output();    //输出3
cout<<a(5)<<endl; //a(5)就调用了operator(5),并a.x=5,返回值是int,也就是5
a.output();         //输出a.x,也是5

原文地址:https://www.cnblogs.com/blogofwu/p/5108687.html