重载运算符

来源:互联网 发布:cad for mac 编辑:程序博客网 时间:2024/04/28 12:07

c++中提供的预定义的类型有限,很多情况下需要使用自定义的数据类型,例如下面的代码是不能通过编译的。

class T

{

........

}

int main()

{

T c,a;

c=a+a;

}

在进行运算符重载时,必须使用一个重载函数,关键字为operator

格式为:

返回值类型 operator 运算符符号(参数说明)

{

//函数体的实现

}

#include<iostream>using namespace std;class Test{public:    Test(int a=0)    {        Test::a=a;    }    friend Test operator+(Test&,Test&);public:    int a;};Test operator+(Test&temp1,Test&temp2){    Test result(temp1.a+temp2.a);    return result;}int main(){    Test a(100);    Test c=a+a;    cout<<c.a<<endl;    return 0;}

如果运算符定义为全局运算符的话,有一个参数的运算符叫做一元运算符,有两个参数的运算符叫做两元运算符;如果定义为类的成员函数的话,一元运算符没有参数,二元运算符有一个参数。这是因为参数自己作为左侧运算符。重载运算符函数既可以定义为全局函数,也可以定义为成员函数。

#include<iostream>using namespace std;class book{public:    book(int i=0,int j=0);    void print();    friend book operator++(book &);private:    int x,y;};book::book(int i,int j){    x=i;    y=j;}void book::print(){    cout<<"x="<<x<<"    y="<<y<<endl;}book operator++(book &temp){    ++temp.x;    ++temp.y;    return temp;}int main(){    book bk(20,30);    bk.print();    ++bk;    bk.print();    return 0;}

使用友元函数重载操作符时,必须使用引用传递参数

0 0
原创粉丝点击