C++面向对象程序设计的一些知识点(5)
2013-11-19 20:19
190 查看
摘要:运算符能给程序员提供一种书写数学公式的感觉,本质上运算符也是一种函数,因此有类内部运算符和全局运算符之分,通过重载,运算符的“动作”更加有针对性,编写代码更像写英文文章。
1、C++标准允许将运算符重载为类成员或者全局的,一般如果是全局的话,为了效率,都是把它们定义为类友元函数。
类型转换-从内置类型到对象
5、运算符重载规则
1、C++标准允许将运算符重载为类成员或者全局的,一般如果是全局的话,为了效率,都是把它们定义为类友元函数。
/* ** 类型转换运算符重载,从内置类型到对象 */ #include <iostream> using namespace std; class Complex { public: Complex(double real, double image) { this->real = real; this->image = image; } Complex(const Complex &c) { real = c.real; image = c.image; cout << "copy constructor called..." << endl; } Complex(double real) { this->real = real; this->image = 0; cout << "one parameter called..." << endl; } ~Complex() {} public: Complex& operator+=(const Complex &c) { real += c.real; image += c.image; cout << "overload operator+= called..." << endl; return *this; } void show() { cout << real; if(image >= 0) cout << "+" << image << "i" << endl; else cout << image << "i" << endl; } private: double real; double image; }; int main() { Complex c1(0, 1.1); c1 += 3.3; c1.show(); int i; cin >> i; return 0; }
类型转换-从内置类型到对象
5、运算符重载规则
运算符 | 规则 |
所有单目运算符 | 建议重载为非static成员函数 |
=、()、[]、->、* | 建议重载为非static成员函数 |
+=、-=、/=、*=、&=、|=、~=、%=、>>=、<<= | 建议重载为非static成员函数 |
所有其他运算符 | 建议重载为全局函数或类的友元函数 |
相关文章推荐
- C++面向对象程序设计的一些知识点(3)
- C++面向对象程序设计的一些知识点(4)
- C++面向对象程序设计的一些知识点(2)
- C++面向对象程序设计的一些知识点(1)
- js中一些小知识点总结--持续更新
- 关于java的一些相关知识点
- 一些有用的小知识点
- C语言一些知识点回顾
- android的一些小知识点
- php中一些知识点(老师不会教哦)
- 我们老师说的一些简单知识点
- 一些小知识点
- CAAnimation动画的一些知识点
- Java基础知识点记录(主要记录一些不常见或者容易忘记的知识点,时刻更新)
- Android开发一些重要知识点_1
- MySQL 一些让人容易忽视的知识点
- 关于Fragment的一些知识点
- html5中的一些小知识点(CSS)
- Activity启动过程的一些知识点
- PHP中最容易忘记的一些知识点总结