47_父子间的冲突

0. 思考:子类中是否可以定义父类中的同名成员?如果可以,如何区分?如果不可以,为什么?

1. 父子间的冲突

  • 子类可以定义父类中的同名成员
  • 子类中的成员将隐藏父类中的同名成员
  • 父类中的同名成员依然存在于子类中
  • 通过作用域分辨符(::)访问父类中的同名成员

编程说明:同名成员变量深度分析

#include <iostream>
#include <string>

using namespace std;

class Parent
{
public:
    int mValue;
    Parent()
    {
        cout << "Parent(): " << "&mValue = " << &mValue << endl;
    }
};

class Child : public Parent
{

public:
    int mValue;
    Child()
    {
        cout << "Child(): " << "&mValue = " << &mValue << endl;
    }
};


int main()
{
    Child c;
    
    c.mValue = 10;
    c.Parent::mValue = 20;
    
    cout << "c.mValue = " << c.mValue << endl;
    cout << "&c.mValue = " << &c.mValue << endl;
    cout << "c.Parent::mValue = " << c.Parent::mValue << endl;
    cout << "&c.Parent::mValue = " << &c.Parent::mValue << endl;

    return 0;
}

输出结果

Parent(): &mValue = 0xbfab5968
Child(): &mValue = 0xbfab596c
c.mValue = 10
&c.mValue = 0xbfab596c
c.Parent::mValue = 20
&c.Parent::mValue = 0xbfab5968

2. 再论重载

类中的成员函数可以进行重载:

  1. 重载函数的本质为多个不同的函数
  2. 函数名参数列表是唯一的表示
  3. 函数重载必须发生在同一个作用域中

3. 问题:子类中定义的函数是否能够重载父类中的同名函数?

不能,子类中定义的函数也会发生同名覆盖,并且子类中父类的作用域不同,不能够重载

编程说明:父子间的函数重载

#include <iostream>
#include <string>

using namespace std;

class Parent
{
public:
    int mValue;
    
    void add(int x)
    {
        mValue += x;
    }
    
    void add(int x, int y)
    {
        mValue +=(x + y);
    }
};

class Child : public Parent
{

public:
    int mValue;
    void add(int x, int y, int z)
    {
        mValue += (x + y + z);
    }
};


int main()
{
    Child c;
    
    c.mValue = 100;
    c.Parent::mValue = 1000;
    
    cout << "c.mValue = " << c.mValue << endl;
    cout << "c.Parent::mValue = " << c.Parent::mValue << endl;
    cout << endl;
    
    c.Parent::add(1);
    c.Parent::add(2, 3);
    c.add(4, 5, 6);
    
    cout << "c.mValue = " << c.mValue << endl;
    cout << "c.Parent::mValue = " << c.Parent::mValue << endl;

    return 0;
}

输出结果

c.mValue = 100
c.Parent::mValue = 1000

c.mValue = 115
c.Parent::mValue = 1006

4. 结论

  • 子类中的函数将隐藏父类的同名函数
  • 子类无法重载父类中的成员函数
  • 使用作用域分辨符访问父类中的同名函数
  • 子类可以定义父类中完全相同的成员函数

5. 小结

  • 子类可以定义父类中的同名成员
  • 子类中的成员将隐藏父类中的同名成员
  • 子类和父类中的函数不能构成重载关系
  • 子类可以定义父类中完全相同的成员函数
  • 使用作用域分辨符访问父类中的同名成员
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容