让我们考虑一个代码示例,显示使用不同级别的继承允许(或不允许)的内容:
class BaseClass {};
void freeStandingFunction(BaseClass* b);
class DerivedProtected : protected BaseClass
{
DerivedProtected()
{
freeStandingFunction(this); // Allowed
}
};
Run Code Online (Sandbox Code Playgroud)
DerivedProtected可以传递给自己,freeStandingFunction因为它知道它来源于BaseClass.
void freeStandingFunctionUsingDerivedProtected()
{
DerivedProtected nonFriendOfProtected;
freeStandingFunction(&nonFriendOfProtected); // NOT Allowed!
}
Run Code Online (Sandbox Code Playgroud)
非朋友(类,函数,等等)无法传递DerivedProtected给freeStandingFunction,因为继承受到保护,因此在派生类之外不可见.私有继承也是如此.
class DerivedFromDerivedProtected : public DerivedProtected
{
DerivedFromDerivedProtected()
{
freeStandingFunction(this); // Allowed
}
};
Run Code Online (Sandbox Code Playgroud)
派生的类DerivedProtected可以告诉它继承自BaseClass,因此可以将自身传递给freeStandingFunction.
class DerivedPrivate : private BaseClass
{
DerivedPrivate()
{
freeStandingFunction(this); // Allowed
}
};
Run Code Online (Sandbox Code Playgroud)
在DerivedPrivate类本身知道它从派生BaseClass,所以本身传递给freeStandingFunction.
class DerivedFromDerivedPrivate : public DerivedPrivate
{
DerivedFromDerivedPrivate()
{
freeStandingFunction(this); // NOT allowed!
}
};
Run Code Online (Sandbox Code Playgroud)
最后,继承层次结构中的一个非友好类无法看到DerivedPrivate继承BaseClass,因此无法将自身传递给freeStandingFunction.
| 归档时间: |
|
| 查看次数: |
4049 次 |
| 最近记录: |