考虑以下类:
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类型的引用。
例如,我想这样做:
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()
我认为这对正在发生的事情更清楚。
发布于 2011-05-19 00:20:31
这个函数的意义是什么?无论如何,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-19 00:28:21
@GMan给出了主要的解决方案。
但是,更详细地注意这个问题可能会很有趣:
const Coord& NamedPoint::coord()
{
return ((Coord)*this);
}
这与以下内容基本相同:
const Coord& NamedPoint::coord()
{
Coord c = *this;
return c;
}
这里很明显,您返回了对堆栈上的临时对象的引用,这使得对它的引用变得无用,因此出现了警告。
现在,在这个例子中,Coord
是基类,因此我们有了@Gman给出的简单解决方案。
在一般情况下,原则是如果你想引用something
,你最好确保something
仍然存在。
https://stackoverflow.com/questions/6052455
复制相似问题