C++ 类的访问控制01

#include <iostream>
using namespace std;

// 类属性或成员变量、成员函数的访问控制
// 用private修饰的成员变量、成员函数,只能在类的内部能使用
// 用public修饰的成员变量、成员函数,在类的内部能使用,在类的外部也能使用
// 用protecetd修饰的成员变量、成员函数,在类的内部能使用,但是在类的外部不能使用
class Test {
public:
    int c; // 如:名字
protected:
    int b;
private:
    int a; // 如:私有信息
};

class Parent {
public:
    Parent(int a=0, int b=0, int c = 0) {
        this->a = a;
        this->b = b;
        this->c = c;
    }
    int c; // 如:名字
    void printSelf() {
        cout << "我是父类" << endl;
    }
protected:
    void printSelf02() {
        cout << "我是父类 protected" << endl;
    }
    int b;
private:
    int a; // 如:私有信息
};

// C++中的继承方式(public、private、protected)会影响子类的对外访问属性
// 判断某一句话,能否被访问(三看法)
// 1)看调用语句,这句话写在子类的内部、外部
// 2)看子类如何从父类继承(public、private、protected)
// 3)看父类中的访问级别(public、private、protected)

// 一般是 class C : public P

// class Child : private Parent  // 一般不用
// class Child : protected Parent // 一般不用
// class Child : public Parent
class Child : public Parent {
public:
    void print() {
        // 子类不能使用父类的private成员变量和成员函数
        //cout << "a: " << a << " b: " << b << " c: " << c << endl;
        cout << " b: " << b << " c: " << c << endl;
    }
protected:

private:

};


void main() {
    //Test t1;
    //t1.b = 10;
    //t1.c = 10;

    Child c1;
    c1.c = 10;
    //c1.b = 11;
    //c1.a = 12;

    c1.print();
    c1.printSelf();
    //c1.printSelf02(); // error: 在子类的外部访问父类的protected属性是不行的。

    system("pause");
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值