1

考虑以下类:

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()——它返回对应于 NamedPoint 的 Coord 类型的引用。

例如,我想要类似的东西:

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

但是我收到有关临时变量的警告,我对此并不感到疯狂。

当然,以下工作:

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

但我宁愿返回一个参考。

有谁知道这是否可以使用继承的类?

很抱歉没有解释函数的重点。我为 Coord 和 NamedPoint 重载了 == 运算符。Coord 会简单地检查 {x,y} 而 NamedPoint 会检查 {id,x,y}。如果我忘记在此 == 测试之前将 NamedPoint 转换为 Coord,我将使用错误的版本。

所以,虽然我意识到

(Coord)np1 == (Coord)np2 

会给我我想要的,我宁愿使用类似的东西

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

我认为更清楚的是发生了什么。

4

2 回答 2

7

该功能的重点是什么?无论如何NamedPoint都可以隐式转换为:Coord

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

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

无论如何,您的函数应该简单地使用这种转换:

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); */
}
于 2011-05-19T00:20:30.597 回答
3

@GMan 给出了主要解决方案。

但是,更详细地注意这个问题可能会很有趣:

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

这与以下内容大致相同:

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

很明显,您正在返回对堆栈上临时对象的引用,这使得对它的引用无用,因此发出警告。

现在在呈现的情况下,Coord是基类,因此我们有@Gman 给出的简单解决方案。

在一般情况下,原则是如果您想要引用something,最好确保它something仍然存在。

于 2011-05-19T00:28:20.510 回答