当前位置: 首页 > news >正文

继承-进阶-易错点

子类同名方法隐藏父类方法

即使调用不匹配也不会再去父类寻找,而是直接报错

//下面代码输出结果:( )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

同名隐藏

http://www.lryc.cn/news/372626.html

相关文章:

  • 【图论应用】使用多路图(multigraph)对上海地铁站点图建模,并解决最短路径问题
  • RabbitMQ安装配置,封装工具类,发送消息及监听
  • iOS接入Flutter
  • 【ubuntu】用户添加root权限
  • 设计通用灵活的LabVIEW自动测试系统
  • C# WinForm —— 35 StatusStrip 介绍
  • 如何应对生活中的不确定性:仁者安仁,知者利仁。
  • C#面:请解释C#接口的显式实现有什么意义
  • STM32项目分享:智能窗帘系统
  • 【算法-力扣】72. 编辑距离(动态规划)
  • Spring 系统架构图
  • 同三维T80005EHS-4K60 4K60 HDMI/SDI编码器
  • React state(及组件) 的保留与重置
  • flask返回的数据怎么是转义后的字符串啊
  • C++17并行算法与HIPSTDPAR
  • 【什么是几度cms,主要功能有什么】
  • 组合和外观模式
  • 设置服务器禁止和ip通信
  • 中文技术文档的写作规范(搬运)
  • 「实战应用」如何用DHTMLX将上下文菜单集成到JavaScript甘特图中(一)
  • Python使用策略模式生成TCP数据包
  • 无文件落地分离拆分-将shellcode从文本中提取-file
  • MySQL 日志(一)
  • XML 编辑器:功能、选择与使用技巧
  • 单例模式(设计模式)
  • 提升你的编程体验:自定义 PyCharm 背景图片
  • SpringCloud与Dubbo区别?
  • 简单Mesh多线程合并,使用什么库性能更高
  • 长亭培训加复习安全产品类别
  • memcached介绍和详解