首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >返回对切片对象的引用(超类型)

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

Stack Overflow用户
提问于 2011-05-19 00:13:16
回答 2查看 479关注 0票数 1

考虑以下类:

代码语言:javascript
运行
AI代码解释
复制
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)
    {
    }
};

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

例如,我想这样做:

代码语言:javascript
运行
AI代码解释
复制
const Coord& NamedPoint::coord()
{
    return ((Coord)*this);
}

但我收到了关于临时变量的警告,我对此并不着迷。

当然,下面的方法是可行的:

代码语言:javascript
运行
AI代码解释
复制
Coord coord()
{
    Coord c = *this;
    return c;
}

但我更愿意返回一个引用。

有没有人知道这是不是可以使用继承的类?

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

所以,当我意识到

代码语言:javascript
运行
AI代码解释
复制
(Coord)np1 == (Coord)np2 

会给我想要的东西,我宁愿使用像这样的东西

代码语言:javascript
运行
AI代码解释
复制
np1.coord() == np2.coord()

我认为这对正在发生的事情更清楚。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-05-19 00:20:31

这个函数的意义是什么?无论如何,NamedPoint都可以隐式转换为Coord

代码语言:javascript
运行
AI代码解释
复制
void foo(Coord& c)
{
    c._x = 5;
}

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

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

代码语言:javascript
运行
AI代码解释
复制
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); */
}
票数 7
EN

Stack Overflow用户

发布于 2011-05-19 00:28:21

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

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

代码语言:javascript
运行
AI代码解释
复制
const Coord& NamedPoint::coord()
{
    return ((Coord)*this);
}

这与以下内容基本相同:

代码语言:javascript
运行
AI代码解释
复制
const Coord& NamedPoint::coord()
{
    Coord c = *this;
    return c;
}

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

现在,在这个例子中,Coord是基类,因此我们有了@Gman给出的简单解决方案。

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6052455

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文