У меня есть два класса: A
и B
, каждый из которых определяет преобразование в B
. A
имеет оператор преобразования в B
, B
имеет конструктор из A
. Не следует ли двузначный вызов static_cast<B>
? Используя g++, этот код компилирует и выбирает конструктор преобразования.
#include<iostream>
using namespace std;
struct B;
struct A {
A(const int& n) : x(n) {}
operator B() const; //this const doesn't change the output of this code
int x;
};
struct B{
B(const double& n) : x(n) {}
B(const A& a);
double x;
};
A::operator B() const //this const doesn't change the output of this code
{
cout << "called A conversion operator" << endl;
return B(double(x));
}
B::B(const A& a)
{
cout << "called B conversion constructor" << endl;
x = (double) a.x;
}
int main() {
A a(10);
static_cast<B>(a); // prints B conversion constructor
}