operator 类型转换及重载

来源:互联网 发布:oracle数据库 select 编辑:程序博客网 时间:2024/06/10 20:30
一、类型转换
类型转换函数的一般形式为 :
operator 类型名()
{实现转换的语句}
在函数名前面不能指定函数类型,函数没有参数.
 
如:
Complex::operator double()
{
return m_dReal;
}
int main()
{
Complex obj(3,4);
double dNum = 0.0;
dNum = 2.5 + obj;
cout<<"dNum="<<dNum<<endl;//dNum=5.5
return 0;
}
如果在Complex类中没有定义类型转换函数operator double,程序编译将出错. 因为不能实现double型数据与Complex类对象相加. 现在,一定了成员函数operator double, 就可以利用它将Complex类对象转换为double型数据. 请注意 : 程序中不必显式地调用类型转换函数,它是自动被调用的,即隐式调用.
 
二、operator 重载圆括号
 
include <iostream>using namespace std;class Time{    int hour;    int minute;    int second;public:    Time( int h=0, int m=0, int s=0 )    {        operator()( h, m, s );    }    //版本0,返回时间表示的秒数    int operator()()    {        return hour*3600+minute*60+second;    }    //版本1,设置为整点    void operator()( int h )    {        operator()( h, 0, 0 );    }    //版本2,设置整小时和分钟    void operator()( int h, int m )    {        operator()( h, m, 0 );    }    //版本3,设置时分秒    void operator()( int h, int m, int s )    {        hour = h;        minute = m;        second = s;    }    friend ostream& operator<<( ostream& os, const Time& ct )    {        os << ct.hour << ';:';;        if( ct.minute<10 )            os << ';0';;        os << ct.minute << ';:';;        if( ct.second<10 )            os << ';0';;        os << ct.second;        return os;    }};int main(){    Time t;    cout << t << endl;    t( 9 );//调用版本1    cout << t << endl;    t( 7, 30 );//调用版本2    cout << t << endl;    t( 0, 10, 20 );//调用版本3    cout << t << endl;    cout << t() << endl;//调用版本0    return 0;}

三、重载解引用
T& operator*() const    {        if(!_ptr)        {            throwNullHandleException(__FILE__, __LINE__);                   }        return *_ptr;    }

四、重载->
#include <iostream>using namespace std;class A{public:void action(){cout << "Action in class A!" << endl;}};class B{A a;public:A* operator->(){return &a;}void action(){cout << "Action in class B!" << endl;}};class C{B b;public:B operator->(){return b;}void action(){cout << "Action in class C!" << endl;}};int main(int argc, char *argv[]){C* pc = new C;pc->action();C c;c->action();getchar();return 0;}

上面代码输出结果是:

Action in class C!
Action in class A!

c是对象,c后面的箭头操作符使用的是重载箭头操作符,即调用类C的operator->()成员函数。此时返回的是类B的对象,所以调用类B的operator->()成员函数,B的operator->()返回的是指针,所以现在可以使用内置箭头操作符了。对B的operator->()返回的指针进行解引用,然后调用解引用后的对象的成员函数action,此时调用的就是类A的action()。这里存在一个递归调用operator->()的过程,最后再使用一次内置含义的箭头操作符。

0 0
原创粉丝点击