【发布时间】:2016-10-10 00:59:59
【问题描述】:
我有一个类B 有两个重载函数int Set(B *); 和int Set(const A&);。类A 需要一个构造函数参数unsigned char。当Set 使用const unsigned char 调用时,其值为0,它被解析为Set(B*),而当传递的值非零时,它解析为Set(const A&)(根据我的预期)。
重载解决方案预期适用于非 const unsigned char,但在 const unsigned char 的值设置为 0 时失败。为什么?
以下代码说明了使用 const 和非 const unsigned char 调用 Set 时的差异
#include <iostream>
using namespace std;
class A{
char m_byteValue;
public:
A(unsigned char c) {
m_byteValue = c;
}
};
class B{
int m_a;
public:
B(){
m_a = 2;
}
int Set(B *);
int Set(const A&);
};
int B::Set(const A& v) {
cout << "I am in the const ref function\n";
return 0;
}
int B::Set(B* p) {
cout << "I am in the pointer function\n";
return 0;
}
int main(){
const unsigned char a = 0;
const unsigned char b = 1;
unsigned char c = 0;
unsigned char d = 1;
B var;
var.Set(a);
var.Set(b);
var.Set(c);
var.Set(d);
return 0;
}
输出(由gcc 4.9.2c++98 编译):
Demo - 在 ideone c++ 5.1 上
I am in the pointer function // Why?
I am in the const ref function
I am in the const ref function
I am in the const ref function
【问题讨论】:
-
Unable to reproduce 在 GCC 4.9.2 中
-
@CoryKramer:在 c++98 中可以重现。
-
嗯,很奇怪。想知道是否仅仅是因为在某处本质上存在
#DEFINE NULL 0,因为它在nullptr之前,所以它认为0应该作为指针传递(因为它认为你正在传递NULL。这个问题提到了@987654323 @ 和 here. -
添加了 C++98 标签,因为它只显示在该版本中。我无法测试 C++03 来确认它的添加。
-
@NathanOliver:另外,在 C++03 中复制。
标签: c++ constants overloading c++98