提示:本笔记是个人学习侯捷C++课程的总结笔记,欢迎来信批评指正!
第一篇 C++基础以及编程规范(一)
第二篇 运算符重载
文章目录
- C++学习笔记
- 一、运算符重载(成员函数)
- 二、运算符重载(非成员函数)
- 1.二元 *** 作符
- 2.一元 *** 作符
- 三、参数为引用(补充上一篇)
- 总结
提示:以下是本篇文章正文内容,下面案例可供参考
inline complex& __doapl(complex* ths,const complex& r)
{
ths->re += r.re;
ths->im += r.im;
return *ths;
}
/*隐藏参数this指针*/
inline complex& complex::operator += (const complex& r)
{
return __doapl (this,r);
}
{
complex c1(2,1);
complex c2(5);
/*先调用重载函数+=,重载函数中再调用__doapl*/
c2 += c1;
}
所有的成员函数都存在隐藏参数this指针,指代调用者。
inline complex operator + (const complex& x,const complex& y)
{
return complex(real(x)+real(y),
imag(x)+imag(y));
}
inline complex operator + (const complex& x,double y)
{
return complex(real(x)+y,imag(x));
}
inline complex operator + (double x,const complex& y)
{
return complex(x+real(y),imag(y));
}
非成员函数重载时,需要写出两个形参,无this。
注意一下,此重载函数返回值并非引用类型,因为此时return返回的只是一个临时变量,不可返回引用类型。typename()临时变量
#include
/*os输出流一直在改变,所以不能在形参中加const*/
/*为了能够连串使用 *** 作符<<,函数返回类型为ostream&,因为非local变量,不加const因为要改变输出流*/
ostream& operator << (ostream& os,const complex& x)
{
return os << '(' << real(x) << ',' << imag(x) << ')';
}
{
complex c1(2,1);
cout << conj(c1);
cout << c1 << conj(c1);
}
<<操作符比较特别,只能写成非成员函数,因为成员函数需要改变隐藏的this(前操作数),但是cout标准库无法改变,故只能写成非成员函数。
inline complex operator + (const complex& x)
{
return x;
}
inline complex operator - (const complex& x)
{
return complex(-real(x),-imag(x));
}
{
complex c1(2,1);
complex c2;
cout<< -c1;
cout<< +c2;
}
三、参数为引用(补充上一篇)
前一篇文章提到,当返回值为引用可以提升传值速度;但是后面学习过程中发现其优点不仅于此。
inline complex&
__doapl(complex* ths,const complex& r)
{
……
return *ths;
}
inline complex&
complex::operator += (const complex& r)
{
return __doapl (this,r);
}
{
complex c1(2,1);
complex c2(5);
complex c3;
/*实参无需知道形参具体是值还是引用*/
c2 += c1;
/*连串赋值是,函数返回值就不能设为void,应该使用类型自身的引用*/
c3 += c2 += c1;
}
1.引用不像指针那样,一定需要区分参数是值还是指针类型;但是如果是引用,实参对应的形参既可以是值也可以是引用。
2.如果再重载函数返回的不是complex类型,那么就无法完成连加 *** 作。
提示:这里对文章进行总结:
1.运算符重载有成员函数和非成员函数之分,成员函数的第一个形参是隐藏的this指针,不可以写;非成员函数则需要写出全部形参。
2.函数中如果返回的是临时变量,就不能使用引用类型作为返回值。
3.如果 *** 作符需要连串 *** 作,那返回值类型必须为 *** 作数类型,不可为void。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)