operator int()
悬赏分:0 -
解决时间:2008-8-21 21:36
![](https://i-blog.csdnimg.cn/blog_migrate/44bcbcaaa8caec969174345bcbfdc16f.gif)
#include<iostream.h>
class C0
{
public:
operator int()//这个东西和下面的"1>>t;"有什么关系?
{
cout<<"call int"<<endl;
}
};
class C1: public C0
{
public:
operator <<(int)
{
cout<<"call <<"<<endl;
}
};
void main()
{
C1 t;
1>>t;
t<<1;
}
class C0
{
public:
operator int()//这个东西和下面的"1>>t;"有什么关系?
{
cout<<"call int"<<endl;
}
};
class C1: public C0
{
public:
operator <<(int)
{
cout<<"call <<"<<endl;
}
};
void main()
{
C1 t;
1>>t;
t<<1;
}
C1 t;
1>>t;//这里要求t是一个int类型,所以要进行类型转换,相当于1>>int(t);
//所以调用操作符重载operator int()
t<<1; //这里调用操作符重载operator <<(int)
1>>t;//这里要求t是一个int类型,所以要进行类型转换,相当于1>>int(t);
//所以调用操作符重载operator int()
t<<1; //这里调用操作符重载operator <<(int)
---
另一例
#include
<
iostream
>
using namespace std;
class A
{
public :
A( int i):a(i) {}
operator int ()
{
return a;
}
private :
int a;
};
int main()
{
A aa( 1 );
int i = aa;
cout << aa << endl;
cout << aa + 5 << endl;
return 0 ;
}
using namespace std;
class A
{
public :
A( int i):a(i) {}
operator int ()
{
return a;
}
private :
int a;
};
int main()
{
A aa( 1 );
int i = aa;
cout << aa << endl;
cout << aa + 5 << endl;
return 0 ;
}