在 const 方法中使用引用
假设我有一个这样的类:
class LinkedList
{
struct Node
{
int StoredValue;
// ...
};
Node& GetNodeReference(std::size_t Index)
{
// ...
return NodeReference;
}
public:
int Get(std::size_t Index) const
{
return GetNodeReference(Index).StoredValue;
}
};
这不会编译,因为 const
方法 Get
使用 GetNodeReference
,它不能是 const
因为它返回一个引用。
我该如何解决这个问题?
Let's say I have a class like this:
class LinkedList
{
struct Node
{
int StoredValue;
// ...
};
Node& GetNodeReference(std::size_t Index)
{
// ...
return NodeReference;
}
public:
int Get(std::size_t Index) const
{
return GetNodeReference(Index).StoredValue;
}
};
This won't compile because the const
method Get
uses GetNodeReference
, which cannot be const
because it returns a reference.
How can I work around this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我不确定您想要实现什么,但您可以提供
GetNodeReference
的两个重载:请注意,第二个重载有两个
const
修饰符,一个在开头返回类型所在行的第一个,以及隐式传递的*this
对象的行尾的一个。为了避免代码重复,您可以在 const 重载的基础上实现非常量重载:
该技术在 Scott Meyers 的 Effective C++ 的第 3 条中进行了讨论。
I'm not sure what you're trying to achieve, but you could provide two overloads of
GetNodeReference
:Note that the second overload has two
const
modifers, one at the beginning of the line for the return type and one at the end of the line for the implicitly passed*this
object.To avoid code repetition, you can implement the non-const overload based on the const overload:
This technique is discussed in Item 3 of Effective C++ by Scott Meyers.
根本不要为列表实现索引
Get
函数。对于新开发人员来说,在循环中使用它,将线性交互转换为多项式迭代,这太容易了。如果您需要这样的功能,请创建一个自由函数,将列表的内置迭代器与 std::advance 结合使用来获取您想要的节点。
如果您绝对需要成员函数,那么正常的方法是@FredOverflow 建议的方法并使用重载(引用他的代码):
Don't implement an indexed
Get
function for lists at all. It will be WAY too easy for a new developer to come in and use it in a loop, turning a linear interation into a polynomial iteration.If you need such a capability, make a free-function that uses the builtin iterators of the list in conjunction with say
std::advance
to get the node you want.If you absolutely need the member function, then the normal approach is the one suggested by @FredOverflow and use overloads (quote his code):
这个怎么样?
编辑:
正如您在评论中看到的那样
应更改为:
How about this?
Edit:
As you can read in the comments
should be changed to:
我建议:
I suggest: