C++基础之访问限制

    科技2024-10-16  23

        Setting limits

        ◆ to keep the client programmer's hands off members they shouldn't touch.

        ◆ to allow the library designer to change the internal workings of the structure without worrying about how it will affect the client programmer.

        C++ access control

        ◆ The mumbers of a class can be cataloged, marked as:

            - public              //公开的

            - private             //只有类自己的成员函数可以访问

            - protected        //只有类自己的成员函数或子类可以访问

        public

        ◆ public means all member declarations that follow are available to everyone

        private

        ◆ The private keyword means that no one can access that member except inside function members of that type.

    【例】

    #include <iostream> using namespace std; class A { private: int i; public: void set(int i); void g(A* p); }; void A::set(int i) { this->i = i; } void A::g(A* p) { cout << p->i << endl; } int main(int argc, const char* argv[]) { A a; A b; b.set(100); a.g(&b); return 0; }

        这说明,private的限制仅仅在编译时刻,同一类的不同对象可以借助指针互相访问其私有的成员

        Friends

        ◆ to explicitly grant access to a function that isn't a member of the structure

        ◆ The class itself controls which code has access to its members.

        ◆ Can declare a global function as a friend, as well as a member function of another class, or even an entire class, as a friend.

    【例】

    struct X; //前向声明 struct Y { void f(X*); }; struct X { private: int i; public: void initialize(); friend void g(X*, int); //Global friend friend void Y::f(X*); //Struct member friend friend struct Z; //Entire struct is a friend friend void h(); }; void X::initialize() { i = 0; } void g(X* x, int i) { x->i = i; } void Y::f(X* x) { x->i = 47; } struct Z { private: int j; public: void ff(X*); }; void Z::ff(X* x) { x->i = 10; }

        friend的授权也是在编译时刻检查的

        class vs. struct

        ◆ class defaults to private

        ◆ struct defaults to public

    Processed: 0.009, SQL: 8