C++ 访问控制(public,protected,private)

1:C++中的继承方式会影响子类的对外访问属性 

public继承:父类成员在子类中保持原有访问级别

private继承:父类成员在子类中变为private成员

protected继承:父类中public成员会变成protected,父类中protected成员仍然为protected, 父类中private成员仍然为private.

 

父类成员访问级别

 

public

proteced

private

public

public

proteced

private

proteced

proteced

proteced

private

private

private

private

Private


通过上面可以简单了解C++的继承关系,如果通过一些特殊的方法也可以访问子类中的非public方法,如下。


#include

using namespace std;

class Father
{
public:
virtual void show()
{
cout << "父类" << endl;
}
};


class Son :public Father
{
private :
virtual void show()
{
cout << "子类" << endl;
}
};


int main()
{
Father *f = new Son;
f->show();
delete f;
return 0;
}

你可能感兴趣的:(C/C++)