在 main(...) 中而不是全局初始化类的静态常量数组成员?
假设 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你无能为力。
您可以创建一个将初始化值的成员函数并调用它。但是,如果它是
static
、private
和const
- 那么你甚至无法做到这一点并且没有选择。您无法在运行时初始化
静态
成员,无法从类外部访问私有
成员(除非您交朋友),并且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
andconst
- then you can't even do that and out of options.You cannot initialize a
static
member at run-time, you cannot access aprivate
member from outside of class (unless you make friends), and you cannot change aconst
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 frommain
, but you can write a wrapper function member to do that for you (or make itpublic
).