码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-03-26 07:56:49      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

#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

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

标签:

原文地址:http://blog.csdn.net/lonelyrains/article/details/50974672

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!