为什么赋值操作调用的是单参构造函数?

Damn_boy 2012-05-28 03:12:34

class WhoWillBeCall
{
public:
WhoWillBeCall()
{
printf("default param Constructor\n");
m_i=1;
};
~WhoWillBeCall(){};

WhoWillBeCall(int i)
{
printf("single param Constructor\n");
};

WhoWillBeCall &operator=(int &ref)
{
printf("operator = ");
return *this;
}
int m_i;
};



WhoWillBeCall test;
test = 1;


结果是

default param Constructor
single param Constructor



WhoWillBeCall &operator=(int &ref)

改为

WhoWillBeCall &operator=(const int &ref)


则是

default param Constructor
operator =


这个...什么原理?

const int &ref 能指代任何的值?
而int ref只能指代int类型的变量?

记得primer里提过
const类型的引用可以指向任何的值
因为编译器会为其生成中间代码
const int& ref = 100.12;
{
int temp = 100.12;
const int&ref = temp;
}
不过忘了这么做的含义了。
...全文
96 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
Damn_boy 2012-06-28
  • 打赏
  • 举报
回复

operator= 针对int的重载版本


WhoWillBeCall &operator=(int &ref)

WhoWillBeCall &operator=(const int &ref)
WhoWillBeCall &operator=(const int val)
WhoWillBeCall &operator=(int val)


比较特殊的是

WhoWillBeCall &operator=(int &ref)版本

int &ref只能处理左值
而其他三个

WhoWillBeCall &operator=(const int &ref)
WhoWillBeCall &operator=(const int val)
WhoWillBeCall &operator=(int val)


都能接收右值

测试代码中
test = 1;

1明显为右值
所以不会触发该重载的operator=

而会触发另一个隐式的类型转换
既将1转化为WhoWillBeCall类型
然后赋值给test

其中就涉及到了单参构造函数的调用
可以把该int的单参构造函数声明为explicit
在编译时就可以看出问题

此外还涉及到了operator=(const WhoWillBeCall &ref)的调用
Fn_1088 2012-05-28
  • 打赏
  • 举报
回复
class WhoWillBeCall
{
public:
WhoWillBeCall()
{
printf("default param Constructor\n");
m_i=1;
}
~WhoWillBeCall(){}

WhoWillBeCall(int i)
{
printf("single param Constructor\n");
}

WhoWillBeCall(const WhoWillBeCall &sc)
{
this->m_i = sc.m_i;
printf("copy constructor \n");
}

WhoWillBeCall& operator=(const WhoWillBeCall &sc)
{
this->m_i = sc.m_i;
printf("=========\n");
return *this;
}

WhoWillBeCall &operator=(/*const */int &ref)
{
printf("operator = \n");
return *this;
}

int m_i;
};
开发者说 2012-05-28
  • 打赏
  • 举报
回复
const int &ref能够接受右值,而int &ref只能接受左值;
WhoWillBeCall test;
test = 1;
1是右值,在const int &ref时,以上语句刚好对应了重载的=;而int &ref时找不到对应的=运算,以上语句就被编译器解释成为了拷贝构造函数的调用进行初始化。
Fn_1088 2012-05-28
  • 打赏
  • 举报
回复
这个还真奇怪了~~~~

64,652

社区成员

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

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