C++什么时候重载用友元,什么时候重载用成员

1.一元运算符,二元运算符
在运算符左和右的变量都是运算符的成员,
所以左右各有一个的是二元运算符如,a+b,a+=b
一元运算符只有一个参数,如&a,*a,+a,-a
2.友元与成员的选择
a.友元不属于任何对象,所以它没有this指针

ex:重载加法 a+b
friend test operator +const test &a,const test &b)
//没有作用域,可以定义多个加法函数,通过哪个重载方法实现只看,传入的参数类型。
{
          test temp.private=a.private+b.private//可以访问private成员
          return temp;//因为返回局部变量所以不能用引用
}

b.成员函数,必定属于一个类,所以会有隐藏的this指针

ex:重载+,a+b
test test:: operator +(const test &b)
{		
		test temp=this->priavte+b,private;
		return temp;
}

选择:
如果是赋值运算:=,+=,-=,这样的赋值运算,最好使用成员函数,返回运算符左侧的引用,这样既可以连续赋值,又可以直接传递引用,不用调用拷贝构造函数将返回的临时变量复制给左侧参数,增加效率。
如果是+,-,/,*这样的运算符,最好使用友元重载,因为左右的参数类型可能不同,比如 int+test,而我们通过友元的参数列表可以轻易的多次重载,设计不同类型的左值和右值的操作.
ex:
friend test operator +(const test &a,const test &b)
friend test operator +(const int &a,const test &b)
friend test operator +(const test &a,const float &b)

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
问题!
我故意返回一个一个函数的局部变量的引用,但是函数却输出了正常的结果!有大佬知道为什么吗?

Ctest.cpp
class Ctest
{
	int m_a;
	int b;
public:
	Ctest(){}
	Ctest(int a,int b):m_a(a),b(b){}
	~Ctest(){
		cout <<this->m_a <<"销毁局部变量" << endl;
	}
	int geta(){ return m_a; }
	friend ostream &operator<< (ostream &out, const Ctest &ts)
	{
		out << ts.m_a <<"----"<< ts.b << endl;
		return out;
	}
	int t(){ return m_a; }
	Ctest &operator+(const Ctest &a)
	{
		Ctest temp;
		temp.m_a= this->m_a + a.m_a;
		return temp;
	}
	/*friend Ctest &operator+(const Ctest &a,const Ctest &b)
	{
		Ctest temp;
		temp.m_a = b.m_a + a.m_a;
		return temp;
	}*/
};
int main()
{

	//Ctest a(222, 2), b(333, 3), c;
	Ctest aa(111, 222), bb(333, 444), cc;
	//c = a + b;
	cc = aa + bb;
	cout << "c:" << cc << endl;
	cout << aa.geta() << endl;
	cout << cc << endl;
	}

在这里插入图片描述

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值