运算符重载

来源:互联网 发布:淘宝卖家销量排行榜 编辑:程序博客网 时间:2024/06/11 10:29

1.运算符

    C++预定义表示对数据的运算,如+,-,*,/,%,^,&,~,|,!,=,<<,>>,!=等等。只能用于基本的数据类型(整形、实型、字符型、逻辑型等)

2.自定义数据类型与运算符重载

    C++提供了数据抽象的手段:用户自己定义数据类型(类)而类的成员函数-》操作对象很不方便
    运算符重载:对抽象数据类型也能够直接使用C++提供的运算符:程序更简洁,代码更容易理解
                            对已有的运算符赋予多重的含义;使同一运算符作用于不同数据类型时-》不同类型的行为
     目的:扩展C++中提供的运算符的适用范围,以用于类所表示的抽象类型
eg.
(5,10i)+(4,8i)=(9,18i);5+4=9;

3.运算符重载

运算符重载的实质是函数重载
返回值类型  operator运算符 (形参表)
{
……
}
 

4.运算符重载为普通函数

#include <iostream>#include <string>using namespace std;class Complex {public:Complex(double r = 0.0, double i = 0.0) {  //构造函数real = r;     //初始化实部虚部imaginary = i;}double real;   //定义两个成员变量double imaginary;};Complex operator+(const Complex &a, const Complex &b) //重载函数{return Complex(a.real+b.real,a.imaginary+b.imaginary);}//类名(参数表)就代表一个对象void main(){Complex a(1, 2), b(2, 3), c;c = a + b;//相当于 operator+(a,b)cout << "When a(1,2)+b(2,3)" << endl;cout << "The real is:"<<c.real<<"\nThe imaginary is:"<<c.imaginary << endl;}

5.运算符重载为成员函数

#include <iostream>#include <string>using namespace std;class Complex {public:Complex(double r = 0.0, double m = 0.0):real(r),imaginary(m){}   //constructorComplex operator+ (const Complex &); //additionComplex operator- (const Complex &); //subtraction//private:double real;   //定义两个成员变量double imaginary;};//Overloaded addition operatorComplex Complex::operator+(const Complex & operand2){return Complex(real+operand2.real,imaginary+operand2.imaginary);}//Overloaded subtraction operatorComplex Complex::operator-(const Complex & operand2){return Complex(real-operand2.real,imaginary-operand2.imaginary);}int main(){Complex a(1.5, 2.8), b(2.3, 3.7), c,d;c = a + b;// x=y.operator+(z)d = a - b;// x=y.operator-(z)cout << c.real << "\t" << c.imaginary << endl;cout << d.real << "\t" << d.imaginary << endl;return 0;}




原创粉丝点击