c++代码赏析之类对象传參

#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

原文地址:https://www.cnblogs.com/jhcelue/p/7191328.html