子类同名方法隐藏父类方法
即使调用不匹配也不会再去父类寻找,而是直接报错
//下面代码输出结果:( )
class A
{
public:
void f(){ cout<<"A::f()"<<endl; }
int a;
};
class B : public A
{
public:
void f(int a){cout<<"B::f()"<<endl;}
int a;
};
int main()
{
B b;
b.f();
return 0;
}
易错:父子类大小关系
private不能被继承(why)
基类中的private成员不可被继承,虽然子类中存在父类中的private成员。之所以说不可继承是因为“继承”通常指的是能否直接访问和使用父类的成员,而不是空间上是否含有相应成员
友元函数不可被继承
类似于 : 父亲的朋友不一定是儿子的朋友
子类和父类共享继承来的静态变量
实例代码:
#include <iostream>
class Parent {
public:
static int sharedStaticVariable;
static void display() {
std::cout << "Parent's sharedStaticVariable: " << sharedStaticVariable << std::endl;
}
};
// 定义并初始化静态成员变量
int Parent::sharedStaticVariable = 42;
class Child : public Parent {
public:
static void displayChild() {
std::cout << "Child's sharedStaticVariable: " << sharedStaticVariable << std::endl;
}
};
int main() {
// 通过父类访问静态变量
std::cout << "Access through Parent:" << std::endl;
Parent::display();
// 通过子类访问静态变量
std::cout << "Access through Child:" << std::endl;
Child::display();
// 修改子类中的静态变量
Child::sharedStaticVariable = 100;
// 再次通过父类访问静态变量
std::cout << "Access through Parent after modification in Child:" << std::endl;
Parent::display();
// 再次通过子类访问静态变量
std::cout << "Access through Child after modification in Child:" << std::endl;
Child::display();
return 0;
}
运行结果:
Access through Parent:
Parent's sharedStaticVariable: 42
Access through Child:
Parent's sharedStaticVariable: 42
Access through Parent after modification in Child:
Parent's sharedStaticVariable: 100
Access through Child after modification in Child:
Parent's sharedStaticVariable: 100