若基类中声明了纯虚函数,继承类必须重写该函数。
virtual void fun1() = 0;
含有纯虚函数的基类是抽象基类,它定义了类的接口,但将接口的实现交给继承类。
派生类的成员和友元只能通过派生类访问基类的受保护对象。
class Base{
protected:
int a;
};
class Inherite: public Base{
friend void f1(Base &b){ //编译器将报错
b.a = 0;
}
friend void f2(Inherite &i){
i.a = 0; //正确
}
};
当一个类A将另一个类B声明为友元时,这种声明只对做出声明的类B有效,B的基类或继承类无法访问A的受保护成员。
继承类可以控制基类中的可访问成员在继承类中的访问属性。若继承类中未声明protected:using Base::a,fun()可以访问Inherite.a。但此处被声明为protected,使fun无法访问。
class Base{
public:
int a;
};
class Inherite: public Base{
protected:
using Base::a;
};
void fun(Inherite &i)
{
i.a = 0; //错误
}
使用class定义的类默认private继承,使用struct定义的类默认public继承。
派生类的作用域嵌套于基类的作用域内。定义在内层作用域的名字将覆盖外层作用域的名字。