一、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;
}