質問

次のクラスを考慮してください。

class Coord
{
public:
    double _x, _y;

    Coord(double x, double y)
    {
        _x = x;
        _y = y;
    }
};

class NamedPoint : public Coord
{
public:
    int _id;

    NamedPoint(int id, double x, double y) :
        Coord(x,y),
        _id(id)
    {
    }
};
.

NamedPoint - Coord()のメンバー関数を作成したいです。

例えば、次のようなものにしたいのですが:

const Coord& NamedPoint::coord()
{
    return ((Coord)*this);
}
.

しかし、私は一時的な変数について警告を受けます、そして私はそれについて夢中ではありません。 もちろん、以下の作品がもちろん:

Coord coord()
{
    Coord c = *this;
    return c;
}
.

しかし、私はむしろ参照を返したいです。

これが継承されたクラスを使用して可能かどうか知っていますか?

関数の点を説明していません。==演算子をordとnamedpointには異なる方法で過負荷にしています。 CORDは単に{x、y}をチェックするだけで、NamedPointは{id、x、y}をチェックします。この==テストの前にNamedPointをCORDにキャストするのを忘れた場合は、間違ったバージョンを使用します。

だから、私はそのを理解しています

(Coord)np1 == (Coord)np2 
.

私が欲しいものを与えるだろう、むしろむしろのようなものを使うのです。

np1.coord() == np2.coord()
.

何が起こっているのもより明確であると思います。

役に立ちましたか?

解決

What's the point of the function? NamedPoint is implicitly convertible to Coord anyway:

void foo(Coord& c)
{
    c._x = 5;
}

NamedCoord nc(0, 1, 2);
foo(nc); // c references the Coord part of nc

Anyway, your function should simply use this conversion:

const Coord& NamedPoint::coord()
{
    // Bad: takes the value of *this and slices off
    // the derived bits, leaving a temporary Coord.
    /* return ((Coord)*this); */

    // Good: takes the value of *this and refers
    // to the base bits, no temporaries.
    return *this;

    // (Same as:)
    /* return ((Coord&)*this); */
}

他のヒント

@GMan gives the main solution.

However, it might be interesting to note in more detail the problem:

const Coord& NamedPoint::coord()
{
    return ((Coord)*this);
}

This is much the same as:

const Coord& NamedPoint::coord()
{
    Coord c = *this;
    return c;
}

Here it is clear that you are returning a reference to a temporary on the stack, which makes the reference to it useless, and hence the warning.

Now in the case presented, Coord is the base class and hence we have the simple solution given by @Gman.

In the general case, the principle is that if you want a reference to something, you better make sure that something will still be around.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top