0

2 つのクラスがあるとします。

// A struct to hold a two-dimensional coordinate.
struct Point
{
    float x;
    float y;
};

// A struct identical to Point, to demonstrate my problem
struct Location
{
    float x;
    float y;
};

Locationaを aに暗黙的に変換したいPoint:

Point somePoint;
Location someLocation;

somePoint = someLocation;

だから、私はこれoperatorを内部に追加しましたPoint

operator Point(Location &other)
{
    // ...
}

Debian でコンパイルするとg++ 4.9.2、次のエラーが表示されます。

error: 'Point::operator Point(Location &other)' must take 'void'

コンパイラは演算子が引数を受け入れないようにしているように思えますが、演算子を間違って使用していない限り、それは正しくないようです。このエラーの背後にある本当の意味は何ですか?

4

2 に答える 2

4

ユーザー定義の変換演算子は、別の型に変換する元の型のメンバー関数として定義れます。署名は(Locationクラス内):

operator Point() const; // indeed takes void
// possibly operator const& Point() const;

別の可能性は、次の変換コンストラクターを提供することですPoint

Point(Location const& location);
于 2016-02-21T20:22:34.020 に答える