您的位置:首页 > 其它

类成员函数返回对象和返回引用的区别

2014-06-07 11:34 281 查看
Base fun1()返回类类型,返回的类类型不能作为左值,但返回的类类型可以直接调用成员函数来修改,如fun1().set(); 返回类类型调用复制构造函数

Base& fun2() 返回类的引用可以作为左值,并且返回的类类型引用可以直接调用成员函数来修改,返回的类类型不会调用复制构造函数。


//返回对象和引用

#include<iostream>
using namespace std;

class Base
{
public:
Base():data(2){}
~Base(){}

Base fun1()
{
cout<<"data= "<<data<<endl;
return *this;
}

Base& fun2()
{
cout<<"data= "<<data<<endl;
return *this;
}

void set(int value)
{
data=value;
cout<<"data= "<<data<<endl;
}
void print()
{
cout<<"data= "<<data<<endl;
}

private:

int data;

};

int main()
{
cout<<"=========Return Object============"<<endl;
Base b1;
b1.fun1().set(5);
b1.print();
cout<<"=========Return Reference============"<<endl;
Base b2;
b2.fun2().set(5);
b2.print();

return 0;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐