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

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

时间:2017-07-16 19:20:15      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:pre   ring   引用   分享   tle   log   view   sdn   opera   

#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++代码赏析之类对象传參

标签:pre   ring   引用   分享   tle   log   view   sdn   opera   

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

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