您的位置:首页 > 编程语言 > C语言/C++

c++运算符重载

2016-01-26 16:01 435 查看

运算符重载

运算符重载的方式就是定义一个函数,在函数体内实现想要的功能,当用到该运算符时,编译器会自动调用这个函数。也就是说,运算符重载是通过函数定义实现的,它本质上是函数重载。

在C++中,运算符重载是很重要的、很有实用意义的。它使类的设计更加丰富多彩,扩大了类的功能和使用范围,使程序易于理解,易于对对象进行操作,它体现了为用户着想、方便用户使用的思想。有了运算符重载,在声明了类之后,人们就可以像使用标准类型一样来使用自己声明的类。类的声明往往是一劳永逸的,有了好的类,用户在程序中就不必定义许多成员函数去完成某些运算和输入输出的功能,使主函数更加简单易读。好的运算符重载能体现面向对象程序设计思想。

运算符重载的格式为:

返回值类型 operator 运算符名称 (形参表列){
//TODO:
}


重载输入运算符>>格式:

istream &operator>>(istream &in,自定义类型名 &形参名)
{
in>>...
return in;
}


重载输出运算符<<格式:

ostream &operator<<(ostream &out,自定义类型名 &形参名)
{
out<<...
return out;
}


注:重载运算符“>>”的函数的第一个参数和函数的类型都必须是istream&类型,第二个参数是要进行输入操作的类。重载“<<”的函数的第一个参数和函数的类型都必须是ostream&类型,第二个参数是要进行输出操作的类。因此,只能将重载“>>”和“<<”的函数作为友元函数或普通的函数,而不能将它们定义为成员函数。

/*****************************************
> File Name : operator_overloading.cpp
> Description : 重载运算符
g++ -g -o operator_overloading operator_overloading.cpp
> Author : linden
> Date : 2016-01-26
*******************************************/
#include <iostream>

using namespace std;

struct Complex {
Complex(){ re = 0; im = 0; }
Complex( double r, double i ) : re(r), im(i)/*构造函数初始值列表*/ {}
Complex operator+( Complex &other );    //运算符“+”重载为成员函数
friend Complex operator-(const Complex & A, const Complex & B);
friend istream &operator>>(istream &in, Complex &other);
friend ostream &operator<<(ostream &out, Complex &other);   //运算符“<<”重载为友元函数
void Display( ) {   cout << re << ", " << im << endl; }
private:
double re, im;
};

// Operator overloaded using a member function
Complex Complex::operator+( Complex &other ) {
return Complex( re + other.re, im + other.im );
}

//重载全局运算符-
Complex operator-(const Complex & A, const Complex & B)
{
Complex C(0.0,0.0);
C.re = A.re - B.re;
C.im = A.im - B.im;
return C;
}

//重载输入运算符
istream &operator>>(istream &in, Complex &other)
{
in >> other.re >> other.im;
return in;
}

//重载输出运算符
ostream &operator<<(ostream &out, Complex &other)
{
cout << other.re << " " << other.im;
return out;
}

int main() {
Complex a = Complex(0.0, 0.0);
Complex b = Complex(0.0, 0.0);
Complex c = Complex(0.0, 0.0);

cin >> a >> b;
/*
在类 Complex 中重载了运算符"+",该重载只对 Complex 对象有效。
当执行c = a + b 语句时,编译器检测到"+"号左边("+"号具有左结合性)是一个 Complex 对象,就会调用运算符重载函数,该语句会被转换为: a.operator+(b)
*/
c = a + b;
cout << a << " + " << b << " = " << c << endl;  //编译系统把“cout << a”解释为operator<<(cout, a)
c = a - b;
cout << a << " - " << b << " = " << c << endl;
//c.Display();

}


运行结果:



参考链接:

C语言中文网:http://c.biancheng.net/cpp/biancheng/cpp/rumen_10/

微学苑:http://www.weixueyuan.net/cpp/rumen/5/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: