c++子类访问父类保护成员,只能通过子类对象

1. 前言

我们知道,对外部来讲,一个类的privateprotected成员,外部都不能直接访问。那么,对子类来说呢?子类如果以public方式继承父类,它还是不能直接访问private成员,并且虽然它可以访问protected成员,也是有限制条件的,就是只能在 类内 类内 类内通过 它自己的实例对象 它自己的实例对象 它自己的实例对象访问。

2. 举例

2.1 外部不能直接访问举例

#include<iostream>
using namespace std;

// 基类
class Base {
    
    
protected:
	int prot_mem;
};

int main()
{
    
    
	Base b;
	b.prot_mem = 0; // 会报错

	return 0;
}

在这里插入图片描述

2.2 子类不能访问举例

#include<iostream>
using namespace std;

// 基类
class Base {
    
    
protected:
	int prot_mem;
};

// 派生类
class Derive :public Base {
    
    
private:
	void f2(Base&);
	int j;
};

void Derive::f2(Base& b) {
    
    
	b.prot_mem = 0; // 会报错
}

int main()
{
    
    
	Derive d;
	d.prot_mem = 0; // 会报错
	
	return 0;
}

在这里插入图片描述
在这里插入图片描述

2.3 子类可以访问举例

#include<iostream>
using namespace std;

// 基类
class Base {
    
    
protected:
	int prot_mem;
};

// 派生类
class Derive :public Base {
    
    
private:
	void f1(Derive&);
	int j;
};

void Derive::f1(Derive& d) {
    
    
	d.j = d.prot_mem = 0; // 可以
}

int main()
{
    
    
	return 0;
}

猜你喜欢

转载自blog.csdn.net/sdhdsf132452/article/details/129853680
今日推荐