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;
}