C++子类继承基类的私有成员吗?

类的大小

类的大小受那些因素影响不是该篇博客的目的,读者自行查阅。

子类继承父类的私有变量吗?

#include <iostream>
#include<typeinfo>
using namespace std;
class parent
{
private:
	int i;
protected:
	int x;
public:
	parent() { x = 0; i = 0; }
	void change() { x++; i++; }
	void display();
};
class son :public parent
{
public:
	son() = default;
	void modify();
};
void parent::display() {
	cout << "x=" << x << endl;
	cout << "i=" << i << endl;
}
void son::modify() { x++; }

int main()
{
	son A; parent B;
	//如果A继承了B的私有变量,A的大小就不仅仅是int x;的大小
	cout << sizeof(A) << endl;//大小为8所以继承了私有成员变量
        A.display(); //能访问到i
	return 0;
}

可以运行发现子类的大小依旧是8而不是4,所以子类继承了基类的私有成员只是无法通过自己的权限去访问父类的私有成员

posted @ 2020-09-28 18:28  Dedicate_labors  阅读(580)  评论(0编辑  收藏  举报
……