【C++】学习笔记草稿版系列11(运算符重载)
2018-02-19 21:25
651 查看
运算符重载和友元之间是如何发生关系的
友元重载,成员重载单目和双目运算符可以重载
通常情况下:
双目运算符重载为成员的话需要一个参数,重载为友元的话需要两个参数
const Complex operator+(Complex& another); friend Complex operator+(Complex & a, Complex & b);
单目运算符重载为成员的话需要0个参数,重载为友元的话需要1个参数。
不必重载的运算符(= &)
// 运算符重载 class Complex { public: Complex(float x = 0, float y = 0) :_x(x), _y(y){} void dis() { cout<<"("<<_x<<", "<<_y<<")"<<endl; } friend Complex operator+(Complex & a, Complex & b); Complex operator+(Complex & another); private: float _x; float _y; }; Complex operator+(Complex & a, Complex & b) { Complex t; t._x = a._x + b._x; t._y = a._y + b._y; return t; } Complex Complex::operator+(Complex & another) { Complex t; t._x = this->_x + another._x; t._y = this->_y + another._y; return t; } int main() { Complex c1(1, 2), c2(2, 3); Complex c = c1 + c2; c1.dis() c2.dis() c.dis() return 0; }
class Complex { public: Complex(float x = 0, float y = 0) :_x(x), _y(y){} void dis() { cout<<"("<<_x<<", "<<_y<<")"<<endl; } Complex & operator+=(const Complex & another); Complex operator-() { return Complex(-this->_x, -this->_y); } private: float _x; float _y; }; Complex & Complex::operator+=(const Complex & another) { this->_x += another._x; this->_y += another._y; return *this; }
流输入输出运算符重载
希望能够实现的情况Complex c(1, 2); cout<<c<<endl; //cout是一个流对象,ostream类型,<<是一个双目运算符 //不能实现:cout.operator<<(x) //可以实现:operator<<(cout, c)
类段的代码
class Complex { public: Complex(float real = 0, float image = 0) :_x(real), _y(image){} void dis() { cout<<"("<<_x<<", "<<_y<<")"<<endl; } friend ostream & operator<<(ostream & os, const Complex &c) { os<<"("<<c._x<<", "<<c._y<<")"<<endl; return os; } friend istream & operator<<(istream & is, Complex &c) { is>>c._x>>c._y; return is; } private: float _x; float _y; };
流输入输出运算符重载
istream & operator>>(istream &, 自定义类 &); ostream & operator<<(ostream &, 自定义类 &);
不可重载的运算符
. ——成员访问运算符.*——成员指针访问运算符
::——域运算符
sizeof——长度运算符
?:——条件运算符
注意事项
一个操作符的左右操作数不一定是相同类型的对象,这就涉及到将该操作符函数定义为谁的友元,谁的成员问题。一个操作符函数,被声明为哪个类的成员,取决于该函数的调用对象(通常是左操作数)。
一个操作符函数,被声明为哪个类的友元,取决于该函数的参数对象(通常是右操作数)。
相关文章推荐
- 【C++】学习笔记草稿版系列5(内联函数)
- 【C++】学习笔记草稿版系列6(强制类型转换)
- 【C++】学习笔记草稿版系列2(函数重载)
- 【C++】学习笔记草稿版系列9(指向类成员的指针)
- 【C++】学习笔记草稿版系列10(友元)
- 【C++】学习笔记草稿版系列4(C++内存管理)
- 【C++】学习笔记草稿版系列1(C到C++类型安全增强)
- 【C++】学习笔记草稿版系列3(引用基础与提高)
- C++学习笔记——运算符重载
- 【C++学习笔记系列】ASSERT函数
- Effective C++ 学习笔记11
- c/c++学习笔记(11)
- PE文件学习系列笔记四-C++实现PE文件的分析
- C++学习笔记 lesson5 运算符重载
- c++ 11学习笔记--智能指针
- c++学习笔记 运算符重载
- 【C++】【学习笔记】【025-027】运算符重载
- C++ FAQ学习笔记 11 章 析构函数
- 【C++】学习小笔记系列-3-cctype中的字符函数
- C++学习笔记4--静态属性 静态方法 虚方法 抽象方法 多态性 析构函数 运算符重载 多继承 虚继承