c++ - const 参数值为 0 的重载决策不正确

标签 c++ constants overloading c++98

我有一个类 B,它有两个重载函数 int Set(B *);int Set(const A&);A 类需要一个构造函数参数 unsigned char。当使用值为 0const unsigned char 调用 Set 时,它被解析为 Set(B*) 而当传递的值不为零时,它解析为 Set(const A&)(按照我的预期)。

重载解析在非 const unsigned char 上正常工作,但在值设置为 0const unsigned char 上失败。为什么?

以下代码说明了使用 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.2 c++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

最佳答案

标准之间的区别在于:

C++98 [conv.ptr]

A null pointer constant is an integral constant expression rvalue of integer type that evaluates to zero.

C++11 [conv.ptr]

A null pointer constant is an integer literal with value zero or a prvalue of type std::nullptr_t.

const unsigned char a = 0; 满足整数常量表达式的 C++98 定义。当然 a 不是右值,但似乎左值到右值的转换适用并且仍然比用户定义的从 unsigned charA

a 不是文字,这就是 C++11 中行为不同的原因。

关于c++ - const 参数值为 0 的重载决策不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37724861/

相关文章:

c++ - 你能在事件处理程序中使用 wxMutex 吗?

c++ - 在没有 ICU 或 boost 的情况下规范化 C++ 中的 unicode 字符?

c++ - 具有 const 参数和重载的函数

C++ curl : treating header and body data differently

c++ - 为什么需要重新声明重载的虚函数?

c++ - 陷阱表示

c++ - 如何使用没有运行时库的 VC++ 内部函数

c++ - 指向 const 对象的指针自动转换为指向对象的指针

c++ - 静态数组常量会影响共享库布局吗?

php - 如何将 is_callable 与 __call 一起使用?