在 C++ 中声明常量数组值

发布于 2024-10-31 03:54:20 字数 244 浏览 0 评论 0原文

例如我有:

int boo[8];
boo[1] = boo[3] = boo[7] = 4;
boo[0] = boo[2] = 7;
boo[4] = boo[5] = boo[6] = 15;

我应该如何将其输入为常量值?我看到类似的问题,但对我没有帮助。

编辑: 还有一个问题,如果索引为 0 1 3 4 5 6 7 的 boo 是常量,但 boo[2] 不是常量呢?有可能做到吗?

For example I have:

int boo[8];
boo[1] = boo[3] = boo[7] = 4;
boo[0] = boo[2] = 7;
boo[4] = boo[5] = boo[6] = 15;

How I should type it as constant values? I saw similar question but it didn't help me.

EDIT:
One more question what about if boo with indexes 0 1 3 4 5 6 7 is constant but boo[2] is not? is it possible to do it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

久伴你 2024-11-07 03:54:21

这是您要找的吗?

const int boo[] = { 7, 4, 7, 4, 15, 15, 15, 4 };

获取指向数组中一项的非常量指针,如下所示:

int * foo = (int*)&boo[2];

Is this what you are looking for?

const int boo[] = { 7, 4, 7, 4, 15, 15, 15, 4 };

Get a non-const pointer to one entry in the array like this:

int * foo = (int*)&boo[2];
很酷又爱笑 2024-11-07 03:54:21

一个不太优雅的解决方案可能是:

const int boo[8] = {7,4,7,4,15,15,15,4};

另一种解决方案可能是:

int boo_[8];
boo_[1] = boo_[3] = boo_[7] = 4;
boo_[0] = boo_[2] = 7;
boo_[4] = boo_[5] = boo_[6] = 15;
const int * boo = boo_;

One not so elegant solution may be:

const int boo[8] = {7,4,7,4,15,15,15,4};

Another solution may be:

int boo_[8];
boo_[1] = boo_[3] = boo_[7] = 4;
boo_[0] = boo_[2] = 7;
boo_[4] = boo_[5] = boo_[6] = 15;
const int * boo = boo_;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文