C++面向对象入门(二)访问权限

C++访问权限表

关键字 访问权限
public
公共权限: 类内可以访问, 类外可以访问
protected
私有权限: 类内可以访问, 类外不可以访问(包括在子类内也不可以访问)
private
保护权限: 类内可以访问, 类外不可以访问(但在子类内可以访问)

代码示例:

#include <iostream>
#include <string>

using namespace std;

class Person {
    //属性:
public:
    //公共权限: 类内可以访问, 类外可以访问
    //姓名
    string name;
private:
    //私有权限: 类内可以访问, 类外不可以访问(包括在子类内也不可以访问)
    //银行卡密码
    string password;
protected:
    //保护权限: 类内可以访问, 类外不可以访问(但在子类内可以访问)
    //汽车
    string car;

    //行为:
public:
    //初始化
    void init(string name, string password, string car) {
        this->name = name;
        this->password = password;
        this->car = car;
    }

    //显示信息
    void showInfo() {
        cout << "Person{姓名: " << name << ", 银行卡密码: " << password << ", 汽车: " << car << "}" << endl;
    }
};

int main() {
    Person p1;
    p1.init("Alan", "nala", "Honda");
    p1.showInfo();
    p1.name = "Lilth";
//    p1.password = "htlit";
    //error: 'std::string Person::password' is private
//    p1.car = "Toyota";
    //error: 'std::string Person::car' is protected
    system("pause");

    return 0;
}

 

公共权限: 类内可以访问, 类外可以访问
posted @ 2020-08-09 11:33  DNoSay  阅读(271)  评论(0编辑  收藏  举报