运算符重载

来源:互联网 发布:关闭windows自动更新 编辑:程序博客网 时间:2024/06/07 00:18

一个我忘记的点:

一元运算符: 一个可以变量可以就运算的运算符 如++,--

二元运算符:+, -

实例:

我们自己实现的类c++当然没有给我们提供类相加相减的操作符,但是间接的给了我们实现的方法。
一个C++ program language中的经典复数例子: 
// Oper.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <iostream>using namespace std;class the_complex{private:double re, im;public:the_complex(double r, double i){re = r;im = i;};~the_complex(){};the_complex operator + (the_complex&c);the_complex operator * (the_complex &c);void show(){cout << re << "  " << im << endl;}};the_complex the_complex::operator+(the_complex &c){return the_complex(re + c.re, im + c.im);}the_complex the_complex::operator * (the_complex &c){return the_complex(re * c.re, im * c.im);}int _tmain(int argc, _TCHAR* argv[]){the_complex A(1, 1.1);the_complex B(2, 2.2);the_complex test1 = A + B;//也可以通过显示调用,两种方法效果相同,类似于调用对象中的成员函数the_complex test2 = A.operator*(B);test1.show();test2.show();getchar();return 0;}
理解:
the_complex operator +(the_complex &c) 可以和void show(void进行比较,两个都是该类的成员函数
第一个函数的返回值是the_complex 类,参数是该类的引用,函数名是operator +
第二个函数的返回值是void,参数是void,函数名是show

用法相同,不过重载运算符可以简写为 a+b,实际写法是a.operator+(b),和调用a.show(void)相同


重载运算符注意问题:

转载别人的比较通俗易懂的文正:点击打开链接
原创粉丝点击