从 const 成员函数返回引用数组
如何从 const 成员函数返回数组引用?
class State{
Chips (&arr() const)[6][7] { return arr_; }
Chips val() const { return val_; }
}
从“const Chips [6][7]”类型的表达式对“Chips (&)[6][7]”类型的引用进行无效初始化
谢谢。
How do I return an array reference from a const member function?
class State{
Chips (&arr() const)[6][7] { return arr_; }
Chips val() const { return val_; }
}
Invalid initialization of reference of type 'Chips (&)[6][7]' from expression of type 'const Chips [6][7]'
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的语法是正确的,但如果 arr_ 是该类的直接成员(很可能是),那么您根本无法返回对此成员的无成本引用。在上面的 arr 方法中,成员 arr_ 被视为具有 const Chips[6][7] 类型。您不能使用此类型来初始化
Chops (&)[6][7]
类型的引用,因为它会破坏常量正确性。为了编译上面的内容,您还需要在返回的引用上使用const
但无论如何,使用 typedef 会更好
You got the syntax right, but if
arr_
is an immediate member of the class (and it probably is), then you simply can't return a non-cost reference to this member. Inside the abovearr
method, memberarr_
is seen as havingconst Chips[6][7]
type. You can't use this type to initialize a reference ofChops (&)[6][7]
type since it would break const-correctness. In order for the above to compile you'd need aconst
on the returned reference as wellBut in any case, you'll be much better off with a typedef
您需要指定该函数返回 Chips 指针。那么,
这就是您正在寻找的。
You need to specify the function as returning a Chips pointer. So,
Is what you are looking for.