请参阅上面的代码和评论。 除了使用访问器/更改器 Settings::gs private之外,还有其他方法可以限制对Settings::gs访问,以便只能通过Settings对象访问它吗? 就这样,任何函数都可以访问Settings::gs无论它是否有权访问Settings对象。 Settings::gs本质上是一个全局对象。
#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; }Please see code above and comments. Besides making Settings::gs private with accessors/mutators, are there other ways to restrict access to Settings::gs so that it can be accessed through Settings objects only? The way it is, any function can access Settings::gs whether it has access to a Settings object or not. Settings::gs is essentially a global object.
最满意答案
我仍然不明白这样做但你可以使用公开引用私有静态成员(我不建议这样做):
struct A { private: struct B { int x, y; } static _b; public: // c++11 initialization, prior you need to initialize b in the // constructor of A B &b{_b}; }; A::B A::_b{0, 0};然后:
int main() { A a1, a2; std::cout << a2.b.x << " "; a1.b.x = 4; std::cout << a2.b.x << std::endl; }输出:
0 4正如@Niall在评论中指出的那样,将引用作为属性将删除默认赋值运算符:
A a1, a2; a2 = a1; // copy assignment is implicitly deleted但是如果你需要它,你可以随时创建自己的,因为你不需要更新b :
struct A { private: struct B { int x, y; } static _b; public: B &b{_b}; A& operator= (A const&) { // ok, no need to update this->b! return *this; } }; A a1, a2; a1 = a2; // okI still don't get the point of doing this but you could use a public reference to a private static member (I would not advise doing that by the way):
struct A { private: struct B { int x, y; } static _b; public: // c++11 initialization, prior you need to initialize b in the // constructor of A B &b{_b}; }; A::B A::_b{0, 0};Then:
int main() { A a1, a2; std::cout << a2.b.x << " "; a1.b.x = 4; std::cout << a2.b.x << std::endl; }Output:
0 4As pointed out by @Niall in the comment, having a reference as an attribute will delete the default assignment operators:
A a1, a2; a2 = a1; // copy assignment is implicitly deletedBut if you need it, you could always create your own since you do not need to update b:
struct A { private: struct B { int x, y; } static _b; public: B &b{_b}; A& operator= (A const&) { // ok, no need to update this->b! return *this; } }; A a1, a2; a1 = a2; // ok更多推荐
发布评论