返回对切片对象(超类型)的引用
考虑以下类:
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()
我认为更清楚正在发生的事情的东西。
Consider the following classes:
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)
{
}
};
I'd like to create a member function of NamedPoint -- coord() -- that returns a reference of type Coord corresponding to the NamedPoint.
For example, I'd like to something like:
const Coord& NamedPoint::coord()
{
return ((Coord)*this);
}
But I get a warning about temporary variables and I'm not crazy about it.
Of course, the following works:
Coord coord()
{
Coord c = *this;
return c;
}
But I'd rather return a reference.
Does anyone know if this is possible using inherited classes?
Sorry for not explaining the point of the function. I'm overloading the == operator differently for Coord and NamedPoint. Coord would simply check {x,y} and NamedPoint would check {id,x,y}. If I forget to cast a NamedPoint to a Coord before this == test, I'll use the wrong version.
So, while I realize that
(Coord)np1 == (Coord)np2
would give me what I want, I'd rather use something like
np1.coord() == np2.coord()
which I think is more clear as to what is going on.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该功能有什么意义?无论如何,
NamedPoint
可以隐式转换为Coord
:无论如何,您的函数应该简单地使用此转换:
What's the point of the function?
NamedPoint
is implicitly convertible toCoord
anyway:Anyway, your function should simply use this conversion:
@GMan 给出了主要解决方案。
然而,更详细地注意这个问题可能会很有趣:
这与以下内容非常相似:
这里很明显,您正在返回对堆栈上临时对象的引用,这使得对其的引用无用,因此会出现警告。
现在,在所呈现的情况下,Coord 是基类,因此我们有@Gman 给出的简单解决方案。
在一般情况下,原则是如果您想要引用
某物
,您最好确保该某物
仍然存在。@GMan gives the main solution.
However, it might be interesting to note in more detail the problem:
This is much the same as:
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 thatsomething
will still be around.