【发布时间】:2016-04-26 10:41:59
【问题描述】:
#include <cstdio>
struct Settings
{
int i1, i2;
Settings(int i1, int i2) : i1(i1), i2(i2) {}
struct GeneralSettings
{
int gi1, gi2;
} static gs;
void do_something() const
{
printf("%d %d %d %d\n", i1, i2, gs.gi1, gs.gi2);
}
};
Settings::GeneralSettings Settings::gs;
int main()
{
Settings s1(0,1);
Settings s2(1,0);
s1.gs.gi1 = 1; // I would like to access GeneralSettings like this only!
Settings::gs.gi2 = 1; // Can i prevent global access like this?
s2.do_something();
return 0;
}
请参见上面的代码和 cmets。除了使Settings::gs private 和accessors/mutators 之外,还有其他方法可以限制对Settings::gs 的访问,使其只能通过Settings 对象访问?事实上,任何函数都可以访问Settings::gs,无论它是否可以访问Settings 对象。 Settings::gs 本质上是一个全局对象。
【问题讨论】:
-
这样做有什么意义?
-
@Holt:避免将
Settings::GeneralSettings暴露给任何地方的每个函数。 -
你现在已经在 Settings 结构中暴露了所有东西,为什么你只关心静态成员?
标签: c++ class struct static-members