类的保护成员与私有成员不能在类外访问。
class A
{
protected:
int c;
};
int _tmain(_In_ int _Argc,char* _In_reads_)
{
A a;
a.c=8;
getchar();
return 0;
}
```编译时不能通过 error C2248: “A::c”: 无法访问 protected 成员(在“A”类中声明)
public继承的情况
#include “stdafx.h”
class A
{
private:
int m_x;
int m_y;
public:
void SetX(int x)
{
m_x=x;
}
protected:
void SetY(int y)
{
m_y=y;
}
int c;
};
class B:public A
{
private:
public:
void set(int t)
{
SetY(t);
}
protected:
};
int _tmain(In int _Argc,char* In_reads)
{
B b;
b.SetX(10);
b.set(99);
getchar();
return 0;
}
public 结论: 派生类的对象不能访问基类的保护成员函数, 派生类可以设计一个接口(成员函数)访问基类的保护成员函数。
protected 继承的情况
#include "stdafx.h"
class A
{
private:
int m_x;
int m_y;
public:
void SetX(int x)
{
m_x=x;
}
protected:
void SetY(int y)
{
m_y=y;
}
int c;
};
class B:protected A
{
private:
public:
void set(int t)
{
SetY(t);
}
protected:
};
int _tmain(_In_ int _Argc,char* _In_reads_)
{
B b;
b.SetX(10);
b.set(99);
getchar();
return 0;
}
编译报错 “A::SetX”不可访问,因为“B”使用“protected”从“A”继承
结论:保护继承的情况下,派生类的对象不能访问基类的公有成员函数。
派生类可以设计一个接口(成员函数)访问基类的公有成员函数。