继承中的同名处理(就近原则)

处理方法

  • 当子类成员和父类成员同名时,子类依然从父类继承同名成员
  • 如果子类有成员和父类同名,子类访问其成员默认访问子类的成员(本作用域,就近原则)
  • 在子类通过作用域::进行同名成员区分(在派生类中使用基类的同名成员,显示使用类名限定符)

成员属性 直接调用先调用子类,如果想调用父类  需要作用域

成员函数  直接调用先调用子类,父类的所有版本都会被隐藏,除非显示用作用域运算符去调用

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;

class NumBase
{
public:
    NumBase()
    {
        this->m_A = 100;
    }
    void func()
    {
        cout << "Base的无参构造" << endl;
    }
    void func(int a)
    {
        cout << "Base (int a)的构造" << endl;
    }
    int m_A;
};
class NumSon :public NumBase
{
public:
    NumSon()
    {
        this->m_A = 200;
    }
    void func()
    {
        cout << "Base的无参构造" << endl;
    }
    int m_A;
};
void test01()
{
    NumSon s;
    cout << s.m_A << endl;  //200  就近原则

    //想调用父类中的m_A
    cout << s.NumBase::m_A << endl; //通过父类名加作用域调用父类m_A

    //s.func(10);     //error  构造函数的重载也会被隐藏掉
    //如果子类和父类拥有同名的属性, 子类会覆盖父类的成员吗? 不会 只会隐藏父类成员
    //如果子类和父类的成员函数名称相同, 子类会把父类的所有同名函数的重载都隐藏掉
    //想调用父类的方法,必须加作用域
    s.NumBase::func(10);

}


int main()
{
    test01();
    system("Pause");
    return 0;
}

结果:

原文地址:https://www.cnblogs.com/yifengs/p/15176715.html