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

nag*_*esh 2 c++ inheritance

我是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;
 }
Run Code Online (Sandbox Code Playgroud)

在上面我声明了与Base类数据成员同名的数据成员,并且我set_values()使用派生的Class Object 调用该函数来初始化数据成员widthheight.

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

Joh*_*web 5

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

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

如果要访问隐藏(或阴影)数据成员,可以使用范围解析:

        int area()
        {
          return (A::width * A::height);
        }
Run Code Online (Sandbox Code Playgroud)