C++中public、protected、private的权限总结

多年前看的东西,写个程序总结一下。

权限总结:

  • 当没有继承时,protected跟private访问权限相同。
  • 当有继承时:
    • 3种继承在其成员函数的访问权限上相同,即,允许通过子类成员函数访问基类的public和protected成员变量,但不能访问基类的private成员变量。
    • protected继承与private继承的子类实例不允许直接访问基类的所有成员变量;而public继承的子类实例只可以直接访问基类的public成员变量,不可以访问private和protected成员变量。

画个表格更清晰一些:

实验代码如下:

#include <iostream>
using namespace std;

class Base
{
public:
    Base(int a, int b, int c) {
        public_base = a;
        protected_base = b; 
        private_base = c; 
    }
    
public:
    int public_base;
protected:
    int protected_base;
private:
    int private_base;
};

class PublicHerit:public Base 
{
public: 
    PublicHerit(int a, int b, int c):Base(a, b, c) {}
    ~PublicHerit(){}
    
public:
    print_base() {
        cout << public_base << endl; 
        cout << protected_base << endl;
        protected_print_public_base();
        protected_print_protected_base();
    }
    
protected:
    protected_print_public_base() {cout << public_base << endl; }
    protected_print_protected_base() {cout << protected_base << endl; }
};

class ProtectedHerit: protected Base 
{
public: 
    ProtectedHerit(int a, int b, int c):Base(a, b, c) {}
    ~ProtectedHerit(){}
    
public:
    print_base() {
        cout << public_base << endl; 
        cout << protected_base << endl;
        protected_print_public_base();
        protected_print_protected_base();
    }
    
protected:
    protected_print_public_base() {cout << public_base << endl; }
    protected_print_protected_base() {cout << protected_base << endl; }
};

class PrivateHerit: private Base 
{
public:
    PrivateHerit(int a, int b, int c):Base(a, b, c){}
    ~PrivateHerit(){}
    
public:
    print_base() {
        cout << public_base << endl; 
        cout << protected_base << endl;
        protected_print_public_base();
        protected_print_protected_base();
    }
    
protected:
    protected_print_public_base() {cout << public_base << endl; }
    protected_print_protected_base() {cout << protected_base << endl; }
};


int main()
{
    PublicHerit *p1 = new PublicHerit(10, 20, 30); 
    ProtectedHerit *p2 = new ProtectedHerit(10, 20, 30); 
    PrivateHerit *p3 = new PrivateHerit(10, 20, 30); 
    
    cout << "Access member variable by member function...\n";
    cout << "Public Herit: \n";
    p1->print_base();
    cout << "Protected Herit: \n";
    p2->print_base();
    cout << "Private Herit: \n";
    p3->print_base();
    
    cout << "Access member variable directly...\n";
    cout << p1->public_base << endl; 
    // cout << p2->public_base << endl;    // Cannot access, Compilation error 
    // cout << p3->public_base << endl;    // Cannot access, Compilation error
    
    return 0;
}

(完)

发布了169 篇原创文章 · 获赞 332 · 访问量 48万+

猜你喜欢

转载自blog.csdn.net/nirendao/article/details/88909581