关于重载指针转换操作符,实现对象名=数组首地址

yshuai1021 2009-05-12 10:40:17
#include <iostream>
using namespace std;



class Conver
{

public:
int *point;
Conver(int s=50){point=new int[50];}
~Conver(){delete []point;}
operator int*(void)const{return point;}
}




int main()
{
Conver c;
cout<<c<<endl;
cout<<c.point<<endl;
eturn 0;
}

比如我定义int a[],数组名a就直接是数组首地址对吧,现在我要实现对象名C直接是数组首地址。
实现这个功能说必须要对强制转换符int*重载,我也开始看不出来哪里用到这个强制转换了。但不重载就实现不了,所以我猜测是不是平时系统隐含调用这个强制类型转换了。
假如上面的程序吧operator那个重载去掉就实现不了了,但MAIN里面并没有显式调用int*,所以猜是不是隐式调用了。

我的意思就是这里为什么一定要重载int*,程序似乎没有用到int*,为什么要重载?
初学C++,请多指教,谢谢!!




...全文
228 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
我看你有戏 2009-05-13
  • 打赏
  • 举报
回复

#include <iostream>
using namespace std;
class Conver
{
public:
int *point;
Conver(int s=50)
{
point=new int[50];
}
~Conver()
{
delete []point;
}
operator int*(void)const
{
return point;
}
};

int main()
{
Conver c;
Conver *p = &c;
int *pNum = c;
cout <<p <<endl;
cout <<pNum <<endl;
cout <<c <<endl;
cout <<c.point <<endl;
return 0;
}

我看你有戏 2009-05-13
  • 打赏
  • 举报
回复


应该是cout帮你调用了(int *)c
papaofdoudou 2009-05-13
  • 打赏
  • 举报
回复

#include <iostream>
using namespace std;



class Conver
{

public:
int *point;
Conver(int s=50)
{
point=new int[50];
}
~Conver()
{
delete []point;
}
operator int*(void)const
{
cout<<"call operator int*[]"<<endl;
return point;
}
int*operator=(int *n)
{
cout<<"call operator="<<endl;
delete []point;
point=n;
return point;
}

} ;




void main()
{
Conver c;
cout <<c<<endl;
cout <<c.point <<endl;

int *a=new int[10];
cout<<a<<endl;
c.operator=(a);

}
上面的程序运行输出时:
call operator int*[]
00372CF0
00372CF0
00372AF8
call operator=
Press any key to continue
可以说明2点:
1.编译器在的确暗中调用了operator int*[],所以你的operator int*[]不是白写的。
2.如果想写 “对象=数组名”这样的方式,还可以重载"operator=",从上面的结果可以看出来,不过在写的过程中要注意堆多次释放的问题,也就是防止多次delete调用,因为你的构造函数中是动态分配的。
papaofdoudou 2009-05-13
  • 打赏
  • 举报
回复
程序用到int*了啊,你在 operator int*里面输出一句看看
operator int*(void)const{
cout<<"call operator int*[]"<<endl;
return point;
}
调用了
yinzhen 2009-05-13
  • 打赏
  • 举报
回复
int *pNum = c;->關鍵是這一句
yshuai1021 2009-05-12
  • 打赏
  • 举报
回复
没太懂~~我这里COUT输出只是验证对象名C已经代表了数组的首地址~
Tesiro 2009-05-12
  • 打赏
  • 举报
回复
应该是在执行是对于<<重载函数没有Conver类对象的版本,所以自动执行到<<重载的void*版本的函数中去, 而此时需要做一个类型的转换, 这样就会引发int*重载函数的运行, 就像是"&"运算符重载函数的执行类似, 你可以试一下将int*换为其它的基类型数据看看, 当然也要把point的类型做一个强转, 效果应该是一样, 由此可以看出此类问题的一般处理方式.

以上只是我个人的一点看法, 不保证一定正确:)
liliangbao 2009-05-12
  • 打赏
  • 举报
回复
帮顶~

65,211

社区成员

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

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