3

私はこれらのコードを持っています:

class Type2 {
public:
  Type2(const Type1 & type);
  Type2(int);
const Type2 & operator=(const Type2 & type2);
//....
};

...
  Type1 t1(13);
  Type2 t2(4);

  t2=t1;

私が理解したように、明示的なキーワードのないType2の1引数コンストラクターは、Type1オブジェクトまたはint値を暗黙的にType2オブジェクトに変換できることを意味する必要があります。

しかし、最後の行ではt2 = t1; 、MS Visual Studioでこのコンパイルエラーが発生します:

....エラーC2679:バイナリ'=':タイプ'Type1'の右側のオペランドをとる演算子が見つかりません(または受け入れ可能な変換がありません)。

MSVisualStudioがt2=t1を主張しているようです。lhs=Type2およびrhs=Type1の代入演算子と一致する必要があります。rhsを暗黙的にt2にキャストしてから、Type2 = Type2演算子を使用してコピーを実行できないのはなぜですか?

4

2 に答える 2

2

I've found the answer. Because my Type1 got a conversion operator

    class Type1 {
    public:
        Type1 (int );
        operator  Type2() ;//casting to Type2

    ....
    };

This is something called "dual-direction implicit conversion"

于 2011-06-19T08:21:22.030 に答える
1

このコード:

#include <iostream>

using ::std::cerr;

class Barney;

class Fred {
 public:
   Fred() { }
   Fred(const Barney &b) { cerr << "Using conversion constructor.\n"; }
};

class Barney {
 public:
   Barney() { }
   operator Fred() const { cerr << "Using conversion operator.\n"; return Fred(); }
};

int main(int argc, const char *argv[])
{
   const Barney b;
   Fred f;
   f = b;
   return 0;
}

gcc 4.6 で次のエラーが生成されます。

g++ -O3 -Wall fred.cpp -o a.out
fred.cpp: In function ‘int main(int, const char**)’:
fred.cpp:23:8: error: conversion from ‘const Barney’ to ‘const Fred’ is ambiguous
fred.cpp:21:17: note: candidates are:
fred.cpp:16:4: note: Barney::operator Fred() const
fred.cpp:10:4: note: Fred::Fred(const Barney&)
fred.cpp:7:7: error:   initializing argument 1 of ‘Fred& Fred::operator=(const Fred&)’

Compilation exited abnormally with code 1 at Sun Jun 19 04:13:53

constここで、 afterを削除するoperator Fred()と、コンパイルされ、変換コンストラクターが使用されます。inconstの宣言からも削除すると、変換演算子が優先されます。bmain

これはすべて、過負荷解決規則に適合します。また、gcc は、変換演算子と変換コンストラクターのどちらかを選択できない場合に、適切なあいまいエラーを生成します。

あなたが与えた例では、変換演算子に a がないことに気付きましたconst。これは、変換演算子または変換コンストラクターの使用があいまいになるケースが決してないことを意味します。

于 2011-06-19T11:17:24.087 に答える