在 main(...) 中而不是全局初始化类的静态常量数组成员?

发布于 2024-12-06 09:10:24 字数 343 浏览 1 评论 0原文

假设 class Myclass { private: static const int myarray[2]; }

如果我想初始化 myarray,我应该将以下语句放在全局范围内:

const int Myclass::myarray[2] = {1,1};

如果我想在 main() 中初始化数组(在某些运行时计算值,例如在 {n1, n2} where n1 处),我该怎么办code> 和 n2 是值根据命令行参数在 main() 运行时计算)

Suppose class Myclass { private: static const int myarray[2]; }

If I wanted to initialize myarray I should put the following statement in global scope:

const int Myclass::myarray[2] = {1,1};

What should I do If I want to initialize my array in main() (at some runtime calculated values eg at {n1, n2} where n1 and n2 are values calculated at runtime in main() based on the command line arguments)

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

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

发布评论

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

评论(1

暖阳 2024-12-13 09:10:24

你无能为力。

您可以创建一个将初始化值的成员函数并调用它。但是,如果它是 staticprivateconst - 那么你甚至无法做到这一点并且没有选择。

您无法在运行时初始化静态成员,无法从类外部访问私有成员(除非您交朋友),并且const 成员一旦初始化就无法更改。

如果你放弃const,那么你可以改变它。您仍然必须在全局范围内初始化,但可以更改值。

请注意,只要它是 private,您就无法从 main 访问它,但您可以编写一个包装函数成员来为您执行此操作(或使它公开)。

There's nothing much you can do.

You could create a member function that would initialize the values, and call it. But, if it's static, private and const - then you can't even do that and out of options.

You cannot initialize a static member at run-time, you cannot access a private member from outside of class (unless you make friends), and you cannot change a const member once initialized.

If you give up const, then you can change it. You still have to initialize at global scope, but you can change values.

Note that as long as its private, you won't be able to access it from main, but you can write a wrapper function member to do that for you (or make it public).

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