C++中的变量的同名隐藏

        同名隐藏是C++中的一个概念,在一个类的继承关系中,子类中定义了一个与父类中同名的成员函数。当这种情况发生时,子类中的函数会隐藏掉所有父类中同名的函数,这意味着在子类中调用这个函数时,会优先调用子类中定义的版本,而不是父类中的版本。

        首先通过C中的代码来进入这个问题

#include<iostream>
using namespace std;
int g_max = 10;
int main()
{
	int g_max = 20;
	cout <<g_max;
}

代码中有两个g_max,我们会优先打印main函数里的g_max,遵循就近原则

如果想要使用全局变量的g_max需要添加::全局解析符表明用意

C++中

#include <iostream>

// 基类 Base
class Base {
public:
    void show() {
        std::cout << "Base class show function called." << std::endl;
    }
};

// 派生类 Derived
class Derived : public Base {
public:
    // 在派生类中定义了一个与基类同名的函数
    // 这将隐藏基类中的同名函数
    void show(int i) {
        std::cout << "Derived class show function with int parameter called, value: " << i << std::endl;
    }
};

int main() {
    Derived d;

    // 调用派生类中的 show 函数
    d.show(10); // 输出: Derived class show function with int parameter called, value: 10

    // 尝试调用基类中的 show 函数
    // 这将导致编译错误,因为基类的 show 函数被隐藏了
    // d.show(); // 编译错误: no matching function for call to 'Derived::show()'

    // 如果要调用基类中的 show 函数,可以使用作用域解析运算符
    d.Base::show(); // 输出: Base class show function called.

    return 0;
}

  • 8
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值