转换构造函数的参数可以隐式转换吗?

Can the argument of a converting constructor be implicitly converted?

现在我正在开展一个项目,其中非常需要两个 classes(A 和 B)之间的可转换性。我创建了一个函数 myFunc() ,它接受一个 class A 的对象作为它的参数,并且我已经向它传递了一个 class B.

的对象

我希望它起作用的原因是 B 可以隐式转换为整数,而 A 可以用整数隐式构造。我预计这两个过程会发生,以便 class B 的对象将隐式转换为 class A 的对象。事实并非如此。

当我尝试将 class B 的对象传递给 myFunc() 时,出现错误:error: could not convert 'b' from 'B' to 'A'.

然而,有趣的是,我可以传入一个 class B 的对象,我将其显式转换为整数,或者传入一个 class A 的显式构造对象,该对象采用 [=28] 的对象=] B 作为它的参数。似乎一行中只能发生一个隐式过程(无论是转换构造函数还是隐式转换)。为什么会这样?有什么办法可以解决这个问题吗?

我知道一个简单的解决方案是在 A 中创建一个将 class B 的对象作为其参数的构造函数,或者在 B 中创建一个运算符来转换 class 的对象] B 到 class A 的对象。但是,出于我的目的,除非绝对必要,否则不应使用这些解决方案。

我还在学习C++(我是从Java过来的)。希望下面的代码能阐明我在说什么。提前感谢您的反馈。

#include <iostream>

// objects of class A can be (implicitly) constructed with an int
struct A {
    A(int) {}
};

// objects of class B can be (implicitly) converted to an int
struct B {
    B(int) {}
    operator int() { return 0; }
};

// myFunc takes an object of class A
void myFunc(A)
{ }

// why can't myFunc convert the argument b like the following: B -> int -> A?
int main()
{
    B b(5);

    // These work:
    myFunc((int) b);
    myFunc(A(b));

    // This does not:
    myFunc(b);
}

注意:上面的代码应该可以正确编译,直到 myFunc(b); 被注释掉。

您要查找的内容在 C++ 中称为 转换序列。要从一种类型转换为另一种类型,只能执行有限的步骤。重要的是,每个可能的类别最多只能有一个步骤。例如。您最多可以有一个数字促销(例如 shortlong。)。对于您的示例,重要的是最多可以有一个 user-defined 转换 。这是或者一个转换构造函数Foo::Foo(Bar)或者一个转换函数 (Bar::operator Foo)。您的示例需要两者。