标签:
#include <iostream>
using namespace std;
class A
{
private:
int x;
public:
A():x(0) { x = 0; cout << "construct" << endl; }
A(const A &a) { x = a.x; cout << "construct copy" << endl; }
~A(){ cout << "destruct" << endl; }
// A operator()(int rhs)
A& operator()(int rhs)
{
x += rhs;
return *this;
}
int getX()
{
return x;
}
};
void main()
{
{
A a;
cout << a(1)(2)(3).getX() << endl;
cout << a.getX() << endl;
}
}
本段代码展示的内容包括:
+ 引用传参
+ 类型对象传参
+ 重载操作符连续调用
在定义A& operator()(int rhs)函数类型声明的情况下,中间不会有新对象,每次操作的均是同一个对象,所以最后输出为:
而在定义A operator()(int rhs)函数类型声明的情况下,中间会产生新的匿名对象,并且自动调用的是拷贝构造函数,打印construct copy。最后输出为
重复调用重载操作的技巧在于返回类型是原类型的引用。
这个技巧可以用来实现对路径的递归访问,实现之前一篇博文的想法:http://blog.csdn.net/lonelyrains/article/details/45093007。
标签:
原文地址:http://blog.csdn.net/lonelyrains/article/details/50974672