奇怪的运算符重载问题

licup 2009-02-19 09:33:17
#include<iostream>
using namespace std;
class three
{
int i;
public:
three(int I=0,int =0):i(I){}
};
class four
{
int x;
public:
four(int X):x(X){}
operator three() const
{
return three(x);
}
};
void g(three){}
void main()
{
four Four(1);
g(Four);
g(1);
}

这个operator three() const重载如何理解?
请大家帮忙看看!
...全文
138 16 打赏 收藏 转发到动态 举报
写回复
用AI写文章
16 条回复
切换为时间正序
请发表友善的回复…
发表回复
cxxer 2009-02-22
  • 打赏
  • 举报
回复
重载类型运算符
speeder53 2009-02-22
  • 打赏
  • 举报
回复
mk
sxbwelcome 2009-02-21
  • 打赏
  • 举报
回复
operator three() const是一个类类型转换
在调用g(Four)时,就会调用类型转换函数完成把Four类型转换成Three类型
因为在定义函数时是这么定义的void g(three)
bfhtian 2009-02-20
  • 打赏
  • 举报
回复
重载的是类型 three
itegel84 2009-02-20
  • 打赏
  • 举报
回复
对头
[Quote=引用 11 楼 pengzhixi 的回复:]
four object;
three(object);//这里就要用到operator three() const将object从four类型转换到three类型。
[/Quote]
ch1oE 2009-02-20
  • 打赏
  • 举报
回复
重载类型运算符。。。恩。。学习了。
pengzhixi 2009-02-20
  • 打赏
  • 举报
回复
four object;
three(object);//这里就要用到operator three() const将object从four类型转换到three类型。
pengzhixi 2009-02-20
  • 打赏
  • 举报
回复
operator three() const是一个Conversion的转换:也就是类型转换的重载。
licup 2009-02-19
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 fallening 的回复:]
引用 2 楼 licup 的回复:
说的不明白。还是谢了。

大家能不能说仔细一点

float f = 1.00987;
int i = (int) f;

four Four(1);
three Three = (three) Fout;

now understand?
[/Quote]


我想知道的是
1)为什么会有这种写法
operator three() const
{
return three(x);
}
2)到底重载的是什么操作符号(以前没见过这种操作符重载)强制类型转换我明白了。
jakqigle 2009-02-19
  • 打赏
  • 举报
回复
自定义的类型转换,知道内部类型有个隐式转换吧,就是c++可以把char型可以自动转换为int型。
char a = 'A';
int int_a = a;
lz代码中在four类些的函数three()就是为了在函数处理在传参数为four对象给g()函数时候,编译器查看g()的声明发现参数应该为three型的,由于在four中重载有three(),就可以由four对象的内容构造一个three型的传递(发生类型转换)给g()函数。
lq651659889 2009-02-19
  • 打赏
  • 举报
回复
operator还能这样用?关注。。。
feng4206yu 2009-02-19
  • 打赏
  • 举报
回复
哦,顶3楼...

class three
{
int i;
public:
three(int I=0,int =0):i(I){}
void print() {cout<<i<<endl;}
};

class four
{
int x;
public:
four(int X):x(X){}
operator three() const
{
return three(x);
}
};
void g(three thr)
{
thr.print();
}

int main()
{
four Four(1);
g(Four); //three thr=(three)Four;
g(1);
return 0;
}
zxianrong 2009-02-19
  • 打赏
  • 举报
回复
隐式类型转换,four可以转换成three
fallening 2009-02-19
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 licup 的回复:]
说的不明白。还是谢了。

大家能不能说仔细一点
[/Quote]
float f = 1.00987;
int i = (int) f;

four Four(1);
three Three = (three) Fout;

now understand?
licup 2009-02-19
  • 打赏
  • 举报
回复
说的不明白。还是谢了。

大家能不能说仔细一点
jEAmIng1012 2009-02-19
  • 打赏
  • 举报
回复
后面参数数量及类型决定。

65,211

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧