从 const 成员函数返回引用数组

发布于 2024-09-19 08:21:44 字数 242 浏览 2 评论 0原文

如何从 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

空气里的味道 2024-09-26 08:21:44

您的语法是正确的,但如果 arr_ 是该类的直接成员(很可能是),那么您根本无法返回对此成员的无成本引用。在上面的 arr 方法中,成员 arr_ 被视为具有 const Chips[6][7] 类型。您不能使用此类型来初始化 Chops (&)[6][7] 类型的引用,因为它会破坏常量正确性。为了编译上面的内容,您还需要在返回的引用上使用 const

...
const Chips (&arr() const)[6][7] { return arr_; }
...

但无论如何,使用 typedef 会更好

...
typedef Chips Chips67[6][7];
const Chips67 &arr() const { return arr_; }
...

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 above arr method, member arr_ is seen as having const Chips[6][7] type. You can't use this type to initialize a reference of Chops (&)[6][7] type since it would break const-correctness. In order for the above to compile you'd need a const on the returned reference as well

...
const Chips (&arr() const)[6][7] { return arr_; }
...

But in any case, you'll be much better off with a typedef

...
typedef Chips Chips67[6][7];
const Chips67 &arr() const { return arr_; }
...
云淡风轻 2024-09-26 08:21:44

您需要指定该函数返回 Chips 指针。那么,

Chips* arr() const;

这就是您正在寻找的。

You need to specify the function as returning a Chips pointer. So,

Chips* arr() const;

Is what you are looking for.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文