C++有访问权限后编程的变化

一、只写或只读变量

(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)越高级的程序语言,越偏向业务,所以就越需要权限管理。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值