私はA
とB
という2つのクラスを持っていて、それぞれが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's conversion operator" << endl;
return B(double(x));
}
B::B(const A& a)
{
cout << "called B's conversion constructor" << endl;
x = (double) a.x;
}
int main() {
A a(10);
static_cast<B>(a); // prints B's conversion constructor
}
興味深い。私はその答えをテストするためにコードを更新しました。この答えは変換コンストラクタを呼び出すのに対して、変換演算子は呼び出されるべきです。 – roro
あなたは正しいと思います。質問はかなり似ているので、冗談のように見えますが、似ていません。 –