考虑以下类:

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)
    {
    }
};
.

我想创建一个名为point - coord()的成员函数 - 返回与命名点对应的类型Coord的引用。

例如,我想到:

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

但我会出现关于临时变量的警告,我对此并不疯狂。

当然,以下作品:

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

但我宁愿回报参考。

是否有任何人都知道使用继承的类是否可以?

抱歉不解释功能的点。对于Coord和NamedPoint,我会超载==运算符。 Coord只会检查{x,y},namedpoint会检查{id,x,y}。如果我忘记在这==测试之前将一个命名点投入到Coord,我将使用错误的版本。

所以,虽然我意识到

(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