您的位置:首页 > 编程语言 > C语言/C++

C++ 中类的访问级别控制(public,protected,private!~~~3p)

2015-12-23 22:44 591 查看
C++ 中通过public,protected,private 3p 关键词来指定类的使用者对类的成员的访问权限;

从类的3种成员角度来讲:

public 成员可以被所有用户访问,包括类本身,类的用户,类的派生类用户

protected 成员可以被类本身,类的派生类用户访问

protected成员可以被类本身访问

类的使用者可以分为三类:  类本身,类的用户(类的对象),类的派生类用户

从类的用户角度来讲,有以下几点:

1 对一个类来说,类本身可以访问其所有成员,包括public,protected,private

2  类的派生类用户可以访问类的public 和protected 成员;

3 类的用户可以访问类的public 成员,可以通过. 或者-> 访问类的public 成员;

类在进行派生时,继承的级别(public,protected或者private继承)会影响基类成员在继承为派生类成员时的访问等级:

public 继承:  基类成员保持自己的访问等级,即基类的public 成员变为派生类的public 成员,基类的protected 成员成为派生类的protected 成员,基类的private 成员成为派生类的private 成员;

protected 继承:  基类的,public,protected 成员成为派生类的protected 成员,基类的private 成员成为派生类的private 成员;

private 继承:基类的所有成员成为派生类的private 成员

实际上,基类成员在派生类中的访问等级是取基类成员自己的访问等级与继承等级的交集

基类成员在派生类中访问等级实际上是对派生类的三类用户而言的,这其中还受一个限制:派生类自己本身只能访问基类的protected 和public 成员

示例代码:

#include <iostream>
#include <iterator>
#include <algorithm>
#include <fstream>
#include <list>
#include <string>
#include <vector>
#include <set>
#include<utility>
#include<functional>

struct Date
{
unsigned year;
unsigned month;
unsigned day;
};

class Human
{
public:
Human():IdentifierID("123456"),Name("inzhiling"),birthDay(){ std::cout<<"Defaulted Constructor of Human is called"<<std::endl; }

std::string getName() { return Name;}
protected:
std::string IdentifierID;
std::string Name;
Date birthDay;
std::string location;
unsigned height; // cm
unsigned weight;
unsigned educatedLevel; //0: less than small school 1: small school 2: middle school 3: master 4:graduate 5: phd
std::string occupation;
unsigned relationState; //0: single 1: has girlfriend or boyfriend 2: married 3:divorced

private:
std::string Name2;
};

class Man : public Human
{
public:
Man()
{
std::cout<<"defaulted constructor of Man is called"<<std::endl;
std::cout<<Name<<std::endl;
//std::cout<<Name2<<std::endl;
}
protected:

private:

};

class Man2 : protected Human
{

public:
Man2()
{
std::cout<<"defaulted constructor of Man is called"<<std::endl;
std::cout<<Name<<std::endl;
//std::cout<<Name2<<std::endl;
}
protected:

private:

};

class Man3 : protected Human
{

public:
Man3()
{
std::cout<<"defaulted constructor of Man is called"<<std::endl;
std::cout<<Name<<std::endl;
//std::cout<<Name2<<std::endl;
}
protected:

private:

};

//test code
int main()
{
Human h1;
std::cout<<h1.getName()<<std::endl;

Man m1;
std::cout<<m1.getName()<<std::endl;

Man2 m2;
// std::cout<<m2.getName()<<std::endl;

Man3 m3;

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: