C++面向对象入门(四)成员私有化

C++中类成员私有化的优点:

1,便于控制成员属性||变量的读写权限
2,便于检验写入属性的合法性

 

示例代码:

#include <iostream>
#include <string>

using namespace std;

/**
 * C++将成员属性||成员变量私有化的优点:
 * 1,便于控制成员属性||变量的读写权限
 * 2,便于检验写入属性的合法性
 */
class Person{
    //属性:
private:
    //私有成员
    //姓名: 可读可写
    string name;
    //年: 可读
    int age;
    //情妇: 可写
    string mistress;

    //行为
public:
    //公共成员

    //修改姓名
    void setName(string name){
        this->name = name;
    }

    //获取姓名
    string getName(){
        return name;
    }

    //获取年龄
    int getAge(){
        return age;
    }

    //更换情妇
    void setMistress(string mistress){
        this->mistress = mistress;
    }

    //初始化
    void init(string name, int age, string mistress){
        this->name = name;
        this->age = age;
        this->mistress = mistress;
    }
};

int main() {
    Person p1;
    p1.init("Adam", 18, "Lilith");
    cout << "Person p1's name is " << p1.getName() << endl;
    p1.setName("Constantin");
    cout << "Person p1's name is " << p1.getName() << endl;
    cout << "Person p1's age is " << p1.getAge() << endl;
    p1.setMistress("Eve");
    system("pause");

    return 0;
}

 

posted @ 2020-08-09 12:14  DNoSay  阅读(309)  评论(0编辑  收藏  举报