一、只写或只读变量
(1)如果class中需要一个变量,但是只能读不能写或者只能写不能读
(2)分析:硬件、os、编程语言都未提供这样的RO或WO的机制,只能间接实现。
(3)解决方案:利用访问权限,将成员变量设计为private,然后通过封装成员的方法实现。
(4)如果只提供read方法就是只读,如果只提供write方法就是只写,如果两个都提供就是可读可写。
(5)这样的成员经常被称为属性,C#等高级编程语言就支持这中编程思想。
二、编程实战
/*person.hpp*/
#ifndef __PERSON_H__
#define __PERSON_H__
#include<string>
using namespace std;
class person
{
//访问权限
public:
//属性
string name; //名字
// int age; //年龄
bool male; //性别
int *pInt; //int类型的野指针
//构造函数和析构函数
person(); //默认构造函数
~person(); //默认析构函数
//方法
void work(void);
void eat(void);
void sleep(void);
void printf(void);
void agewrite(int a); //提供一个age变量的写方法
int ageread(void); //提供一个age变量的写方法
private:
int age; //年龄,我们希望age只能些不能读
};
#endif
/*person.cpp*/
#include "person.hpp"
#include <iostream>
using namespace std;
//引用class中函数的方法
void person::work(void)
{
if (this->male)
{
cout << this->name << " coding" << endl;
}
else
{
cout << this->name << " shopping" << endl;
}
eat(); //在同一个类中可以直接调用类里面的方法
}
void person::eat(void)
{
cout << this->name << " eat "<< age << endl;
}
void person::printf(void)
{
cout << " name =" << name << endl;
cout << " age =" << age << endl;
cout << " male =" << male << endl;
}
void person::sleep(void)
{
cout << "value of this->pIn =" << *pInt << endl;
}
//age变量的写方法
void person::agewrite(int a)
{
this->age = a;
}
//age变量读方法
int person::ageread(void)
{
return age;
}
person::person()
{
//默认构造函数是空的
cout << "default constructor" << endl;
}
person::~person()
{
cout << "userdefine destructor" << endl;
}
/*main.cpp*/
#include <iostream>
#include "person.hpp"
using namespace std;
int main(void)
{
//人的一天生活
string s1 = "linux";
person pPerson; //创建一个person对象
pPerson.name = "zhangsan"; //在类的外部可以通过对象访问变量
// pPerson.age = 0;
pPerson.agewrite(23);
pPerson.male = 0;
/*
pPerson.printf();
pPerson.eat();
pPerson.work();
pPerson.eat();
*/
// pPerson.work(); //public中,在类的外部可以通过对象访问方法和
// pPerson.eat();
//变量读方法
int age = pPerson.ageread();
cout << "age " << age << endl;
getchar();
return 0;
}
三、为什么C语言不需要这些
(1)C主要做逻辑开发和OS内核开发,都是独立一体化的程序,不隔离,所以不需要也秘法权限管控。
(2)C程序一般规模小,不需要权限管控
(3)C程序强调性,二权限管控会在一定程度牺牲性能。
(4)越高级的程序语言,越偏向业务,所以就越需要权限管理。