可见性

比较简单,很好理解,长话短说

=v= 外部的类 派生类 同一个类
private 不可访问 不可访问 可以访问
protected 不可访问 可以访问 可以访问
public 可以访问 可以访问 可以访问
#include<iostream>

using namespace std;

class A {
private:
    int x;
protected:
    int y;
public:
    int z;
    A(int x = 0, int y = 0, int z = 0) {
        A::x = x;
        A::y = y;
        A::z = z;
    }
    void print() {
        cout << A::x << endl;
        cout << A::y << endl;
        cout << A::z << endl;
    }
};

class B :public A{
public:
    B(int y, int z) {
        B::y = y;
        B::z = z;
    }
    void print() {
        //cout << B::x << endl; 错误,x是protected,派生类无法访问
        cout << A::y << endl;
        cout << A::z << endl;
    }
};  

int main(void) {
    A test(1, 2, 3);
    test.print();
    B test2(1, 2);
    test2.print();
    //x与y分别是private和protected,不能在类外访问
    //cout << test.x << endl;
    //cout << test.y << endl;
    cout << test.z << endl;
    return 0;
}
最后修改:2023 年 04 月 28 日
如果觉得我的文章对你有用,请随意赞赏