protected(保护)访问权限

一个类, 如果希望, 它的成员, 可以被自己的子类(派生类)直接访问,
但是, 又不想被外部访问那么就可以把这些成员, 定义为 protected访问权限!!!

#include <string>

using namespace std;

class Father {
    
    
public:
	Father(const char *name, int age){
    
    }
	~Father(){
    
    }
	
	string getName() {
    
    return name;}
private:
	string name;
protected:
	int age;
};

访问权限总结:
1.public
外部(指对象)可以直接访问.
可以通过对象来访问这个成员

	Fahter  wjl("王健林", 65);
	wjl.getName();

2.private
外部(指对象)不可以访问
自己的成员函数内, 可以访问

	Fahter  wjl("王健林", 65);
	wjl.name; // 错误!!!

Father内的所有成员函数内, 可以直接访问name

3.protected
protected和private非常相似,都不能从外部(指对象)访问!

	Fahter  wjl("王健林", 65);
	wjl.age; // 错误!!!

protected和private的唯一区别:
protecte: 子类的成员函数中可以直接访问
private: 子类的成员函数中不可以访问

例如:

#include <string>

using namespace std;

class Son : protected Father {
    
    
public:
	Son(const char *name, const char *game, int age);
	~Son();
	
	string getGame() const;
	void description() const;
private:
	string game;
};

子类Son中,关于string description() const函数的实现要这样写:

void Song::description() const {
    
    
	cout << "name:" << getName() << "-age:" << age << "-game:" << game << endl;
}

子类Son的成员函数description()访问private成员name时,通过调用函数getName(),而不能直接访问name数据!

猜你喜欢

转载自blog.csdn.net/weixin_46060711/article/details/123932852