【问题标题】:Implicit conversion from char to int for constructors in C++C++ 中构造函数从 char 到 int 的隐式转换
【发布时间】:2021-11-10 11:41:08
【问题描述】:
class A {
    int x;
    std::string s;
public:
    A(std::string _s): x(0), s(_s) {
        std::cout << "\tA(string)\n" ;
    }
    A(int _x): x(_x), s("") {
        std::cout << "\tA(int)\n" ;
    }
    A(const A &other): x(other.x), s(other.s) {
        std::cout << "\tA(A& other)\n" ;
    }
};

int main() {
    std::string str = "Hello";
    A obj_1(str);
    A obj_2 = str;
    A obj_3(10);
    A obj_4 = 10;
    char ch = 'a';
    A obj_5 = ch;               // How is this working?
    // A obj_6 = "Hello";        // And not this?
    const char *ptr = "Hello";
    // A obj_7 = ptr;            // or this?

    return 0;
}

执行此代码时,输​​出为:

        A(string)
        A(string)
        A(int)
        A(int)
        A(int)

据我了解,obj_1obj_3 是使用各自的 ctor 直接创建的。对于obj_2obj_4,编译器通过调用它们各自的ctor 进行隐式转换(因此在每种情况下只需要1 次隐式转换)。但是,对于obj_5,编译器首先必须将 char 转换为 int,然后再进行一次隐式转换以调用 int-ctor。但是 C++ 标准只允许 1 次隐式转换。那么这里发生了什么?

此外,在这种情况下,"Hello" 应首先转换为 std::string,然后再进行一次隐式转换以调用 string-ctor。但这不起作用。

【问题讨论】:

    标签: c++ constructor c++17 implicit-conversion


    【解决方案1】:

    但 C++ 标准只允许 1 次隐式转换。

    这不正确。

    来自cppreference

    隐式转换序列按以下顺序由以下组成:

    1. 零个或一个标准转换序列;
    2. 零次或一次用户定义的转换;
    3. 零个或一个标准转换序列。

    从语言的角度来看,const char[N] -> std::string(或const char*std::string)是用户定义的转换。因此,注释掉的行是错误的。另一方面,

    A obj_5 = ch;               // How is this working?
    

    很好,因为只涉及一个用户定义的转换。

    【讨论】:

      猜你喜欢
      • 2018-05-30
      • 1970-01-01
      • 2013-11-02
      • 1970-01-01
      • 2014-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多