返回对切片对象的引用(超类型)

jed*_*rds 1 c++ inheritance reference object-slicing

考虑以下类:

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)
    {
    }
};
Run Code Online (Sandbox Code Playgroud)

我想创建NamedPoint的成员函数--coord() - 返回与NamedPoint对应的Coord类型的引用.

例如,我想要像:

const Coord& NamedPoint::coord()
{
    return ((Coord)*this);
}
Run Code Online (Sandbox Code Playgroud)

但我收到关于临时变量的警告,我并不为此感到高兴.

当然,以下工作:

Coord coord()
{
    Coord c = *this;
    return c;
}
Run Code Online (Sandbox Code Playgroud)

但我宁愿返回一个参考.

有没有人知道使用继承类是否可行?

很抱歉没有解释该功能的要点.我为Coord和NamedPoint以不同的方式重载了==运算符.Coord只需检查{x,y},NamedPoint将检查{id,x,y}.如果我忘记在此==测试之前将一个NamedPoint强制转换为Coord,我将使用错误的版本.

所以,虽然我意识到这一点

(Coord)np1 == (Coord)np2 
Run Code Online (Sandbox Code Playgroud)

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

np1.coord() == np2.coord()
Run Code Online (Sandbox Code Playgroud)

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

GMa*_*ckG 7

这个功能有什么意义?无论如何NamedPoint都可以隐式转换Coord:

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

NamedCoord nc(0, 1, 2);
foo(nc); // c references the Coord part of nc
Run Code Online (Sandbox Code Playgroud)

无论如何,你的功能应该只使用这个转换:

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); */
}
Run Code Online (Sandbox Code Playgroud)