这个 C++ 隐式转换是如何发生的?

How is this C++ implicit conversion occurring?

提前为这个问题道歉。自从我使用 C++ 以来已经有一段时间了,而且我似乎找不到能够回答我的问题的确切教程。我认为这是一个隐式转换的例子,但我不确定。

代码:

class Square
{
public:        
    Square(int size) : size{size}
    {
    }

    int getSize() const
    {
        return size;   
    }

private:
    int size;
};

void doSomething(Square square)
{
    cout << "doSomething called with " << square.getSize() << endl;   
}

int main()
{
    // Should be passing in a Square type here, but instead passing an int.
    doSomething(23);
    return 0;
}

输出:

doSomething called with 23

问题:

  1. 这是隐式转换的例子吗?
  2. 这是怎么发生的?如果 link 更详细地解释了这一点,我会很满意。对于它的价值,我已经完成了 the cplusplus.com explanation of Type conversions

谢谢!

简而言之:因为 Square square = 23; 是有效的,调用 doSomething(23) 匹配签名 doSomething(Square square) ;这就是重载决策中候选函数选择的工作原理。

如果 doSomething 的其他重载也与调用匹配,则重载将根据每个重载所需的转换进行排名。

代码 Square square = 23; 有效,因为 Square 有一个 converting constructor