ネイティブタイプのような構造体間の明示的な変換を強制したい:
int i1;
i1 = some_float; // this generates a warning
i1 = int(some_float): // this is OK
int i3 = some_float; // this generates a warning
代入演算子とコピーコンストラクターを使用して同じことを行うことを考えましたが、動作が異なります。
Struct s1;
s1 = other_struct; // this calls the assignment operator which generates my warning
s1 = Struct(other_struct) // this calls the copy constructor to generate a new Struct and then passes that new instance to s1's assignment operator
Struct s3 = other_struct; // this calls the COPY CONSTRUCTOR and succeeds with no warning
Struct s3 = other_struct;
デフォルトのコンストラクターを使用して3番目のケースのコンストラクトs3を取得し、代入演算子を呼び出すためのトリックはありますか?
これはすべて、必要に応じてコンパイルおよび実行されます。C ++のデフォルトの動作は、新しいインスタンスを作成してコピーコンストラクターを一度に呼び出すときに、代入演算子の代わりにコピーコンストラクターを呼び出すことです(つまり、;ではありませんMyStruct s = other_struct;
。それを回避するためのトリックがあるかどうか疑問に思っています。 。MyStruct s(other_struct)
MyStruct s; s = other_struct;
編集:「明示的な」キーワードは私が必要としていたものです!
class foo {
foo(const foo& f) { ... }
explicit foo(const bar& b) { ... }
foo& operator =(const foo& f) { ... }
};
foo f;
bar b;
foo f2 = f; // this works
foo f3 = b; // this doesn't, thanks to the explicit keyword!
foo f4 = foo(b); // this works - you're forced to do an "explicit conversion"