设为首页 加入收藏

TOP

C++ 成员函数返回引用,三种获取返回值的效果
2015-11-21 00:59:03 来源: 作者: 【 】 浏览:2
Tags:成员 函数 返回 引用 获取 效果

这个实验需要以下的代码:

?

class Test
{
public:
    Test(){cout << "Test" << endl;}
    ~Test(){cout << "~Test" << endl;}
    Test(const Test &right)
    {
        cout << "Test(const)" << endl;
        this->a = right.a;
    }
    Test & operator =(const Test & right)
    {
        cout << "operator=" << endl;
        if(&right == this){
            return *this;
        }
        this->a = right.a;
        return *this;
    }

    Test & geta(){return *this;}
    int getdata(){return a;}
private:
    int a;
};

int main()
{
    Test a;
    cout << "#1#" << endl;
    Test s = a.geta();
    cout << "#2#" << endl;
    Test &p = a.geta();
    cout << "#3#" << endl;
    Test q;
    q = a.geta();
    return 0;
}

上述代码的运行结果为:

?

?

Test
#1#
Test(const)
#2#
#3#
Test
operator=
~Test
~Test
~Test

分析:

?

#1#(Test s = a.geta();):此条语句生成了一个新的s对象。调用复制构造函数对其进行了初始化;

#2#(Test &p = a.geta();):此条语句是以引用名p来指向geta()函数返回的对象,这里没有多余的操作;

#3#(Test q; q = a.geta();):这两条语句,首先调用参数为空的构造函数,生成对象q。接下来通过调用operator=函数对q进行了赋值;

以上三种获取函数返回值的方式都可以正确执行。以上分析可以看出,这三种方式存在执行效率的差别。而在C++中,STL容器模板的 front() 成员函数均会返回引用。因此,这里可以根据是否需要对容器中的值进行修改而决定需要哪个方法。甚至这三种情况的选用不当也会有内存泄露的危险。

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇UVA 11134 Fabled Rooks 优先队列 下一篇POJ2029:Get Many Persimmon Tree..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: