C++访问权限问题

一、public访问权限是全局的

(1)pubilc的成员变量,在类的方法中可以直接访问
(2)public的成员变量,在任何外部代码中可以通过类的对象直接访问。
(3)public的成员方法,在类内其他成员可以直接调用。
(4)pubilc的成员方法,在任何外部代码中可以通过类的对象来直接访问。

二、private访问权限

(1)private的成员变量,在内部可以直接访问。
(2)private的成员变量,在类的外部不能通过对象访问。
(3)private的成员方法,在内部可以直接访问
(4)private的成员方法,不能嫩=通过对象访问

三、更多的访问权限

(1)protected是第三种访问权限修饰符,如果有必要也能够有更多的权限修饰符。
(2)访问权限加类的继承、static、friend等特性后才能更加显出复杂性和功能。

四、编程实战

/*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);

	private:
		int age;       //年龄
		void eat(void);
	};


#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" << 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;

}





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.male = 0;
	/*
	pPerson.printf();
	pPerson.eat();
	pPerson.work();
	pPerson.eat();
	*/

	pPerson.work();     //public中,在类的外部可以通过对象访问方法和
//	pPerson.printf();   //在private中,在类的外部不可以通过对象访问方法和




	getchar();
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值