基类和派生类中的数据成员相同

same data members in both base and derived class

本文关键字:数据成员 派生 基类      更新时间:2023-10-16

我是C++编程的新手,我正在阅读继承概念,我对继承概念有一个疑问,即:如果基类和派生类具有相同的数据成员,会发生什么。也请通过我的代码如下:

#include "stdafx.h"
#include <iostream>
using namespace std;
class ClassA
{
   protected :
       int width, height;
   public :
       void set_values(int x, int y)
       {
           width = x;
           height = y;
       }
};
class ClassB : public ClassA
{
    int width, height;
    public :
        int area()
        {
            return (width * height);
        }
};
int main()
{
    ClassB Obj;
    Obj.set_values(10, 20);
    cout << Obj.area() << endl;
    return 0;
 }

在上面的例子中,我声明了与基类数据成员同名的数据成员,并使用派生的类对象调用了set_values()函数来初始化数据成员widthheight

当我调用area()函数时,为什么它会返回一些垃圾值,而不是返回正确的值。只有当我在派生类中声明与基类数据成员同名的数据成员时,才会发生这种情况。如果我移除派生类中声明的数据成员,则工作正常。那么,派生类中的声明有什么问题呢?请帮帮我。

B中的widthheight数据成员隐藏了A中的数据成员(或阴影)。

在这种情况下,它们没有任何用处,应该删除

如果您想访问隐藏(或阴影)数据成员,您可以使用范围分辨率:

        int area()
        {
          return (A::width * A::height);
        }