C++运算符重载(1) - 介绍
2015-05-26 01:18
295 查看
1.运行符重载
C++中,可以在定义的类中使用操作符。例如,可以对于一个String类,重载操作符+,这样就可以在两个string之间直接使用+。一个简单的例子:
#include<iostream> using namespace std; class Complex { private: int real, imag; public: Complex(int r = 0, int i =0) {real = r; imag = i;} //两个复数相加时,此函数会被调用 Complex operator + (Complex const &obj) { Complex res; res.real = real + obj.real; res.imag = imag + obj.imag; return res; } void print() { cout << real << " + i" << imag << endl; } }; int main() { Complex c1(10, 5), c2(2, 4); Complex c3 = c1 + c2; // 调用"operator+"的例子 c3.print(); }输出:
12 + i9
2.运算符函数与普通函数的区别
运算符函数与普通函数一样。唯一的不同在于,运算符函数的名字通常由operator关键字加上运算操作符组成。当相关的操作符被使用时,则重载的操作符函数会被调用。下面是一个全局运算符函数的例子:
#include<iostream> using namespace std; class Complex { private: int real, imag; public: Complex(int r = 0, int i =0) {real = r; imag = i;} void print() { cout << real << " + i" << imag << endl; } // 将全局的重载运算符函数,做为类的友元函数,这样可以访问私有数据 friend Complex operator + (Complex const &, Complex const &); }; Complex operator + (Complex const &c1, Complex const &c2) { return Complex(c1.real + c2.real, c1.imag + c2.imag); } int main() { Complex c1(10, 5), c2(2, 4); Complex c3 = c1 + c2; // 调用"operator+" c3.print(); return 0; }
3.不能被重载的运算符
除了少数的运算符,绝大部分都能被重载。下面是不能被重载的操作符列表:. :: ?: sizeof为何上面4种操作符不能重载?
可以参考 http://www.stroustrup.com/bs_faq2.html#overload-dot
4.关于运算符操作的重要信息:
1) 为了让操作符重载能工作,至少得有一个操作对象是用户自定义的类对象。2) 赋值操作符: 编译器会自动的给每个类创建一个默认的赋值操作符。它会将所有成员从右边赋给左边,大多数情况下可以正常工作(不正常的地方与拷贝构造一样)。
3) 转换操作符: 我们可以自定义转换操作符,用来将一个类型转换成另外类型。
#include <iostream> using namespace std; class Fraction { int num, den; public: Fraction(int n, int d) { num = n; den = d; } // 转换操作符:返回float值的分数 operator float() const { return float(num) / float(den); } }; int main() { Fraction f(2, 5); float val = f; cout << val; return 0; }输出:
0.4
转换操作符必须是一个成员方法。 其它的操作符可以是成员方法或者全局方法。
4) 任何只带有一个参数的构造函数,都可以当做转换构造函数使用,意味着可以用于隐式转换。
#include<iostream> using namespace std; class Point { private: int x, y; public: Point(int i = 0, int j = 0) { x = i; y = j; } void print() { cout << endl << " x = " << x << ", y = " << y; } }; int main() { Point t(20, 20); t.show(); t = 30; // t的x成员会变成30 t.print(); return 0; }输出:
x = 20, y = 20
x = 30, y = 0
本系列的后续文章会,会讨论一些重要操作符的重载,例如 new, delete, comma, function call, arrow, 等.
更多参考:
http://en.wikipedia.org/wiki/Operator_overloading
相关文章推荐
- C++运算符重载(4) .*和.->操作符介绍
- 和C++运算符重载相关的问题
- C++运算符重载的规则
- C++运算符重载的方法
- C++中不能被重载的运算符介绍
- [转]Java中继承、多态、重载和重写介绍
- C++运算符重载详细解说及代码编写
- [置顶] # c++运算符重载之 前置++, 后置++, 负号运算符, 类型转换函数, 以及输入输出运算符
- C++运算符重载,友元函数
- C++运算符重载(5) - explicit关键字的使用
- C++运算符重载
- 掌握C++运算符重载
- C++运算符重载:怎样定义函数才“符合常理”
- C++运算符重载小程序
- C++运算符重载(以复数为例)
- C++运算符的重载
- C++运算符重载:operator
- C++运算符重载的妙用
- c++运算符重载
- C++运算符重载