基类和派生类中的数据成员相同
same data members in both base and derived class
我是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()
函数来初始化数据成员width
和height
。
当我调用area()
函数时,为什么它会返回一些垃圾值,而不是返回正确的值。只有当我在派生类中声明与基类数据成员同名的数据成员时,才会发生这种情况。如果我移除派生类中声明的数据成员,则工作正常。那么,派生类中的声明有什么问题呢?请帮帮我。
B
中的width
和height
数据成员隐藏了A
中的数据成员(或阴影)。
在这种情况下,它们没有任何用处,应该删除
如果您想访问隐藏(或阴影)数据成员,您可以使用范围分辨率:
int area()
{
return (A::width * A::height);
}
相关文章:
- 派生类是否可以在抽象工厂设计模式中具有数据成员
- C++ 使用派生类方法更改基类数据成员
- 如何使用数据成员填充派生类的对象到基类的指针数组中
- 以基类作为数据成员的派生类?
- 无法访问派生类函数内的基类的受保护数据成员
- 派生类不从基类继承数据成员
- 基类数据成员类型取决于派生类
- 使用来自基类方法的派生类数据成员
- 我们可以从派生类更改基类的数据成员吗?
- 如何在C 中的派生类中分配数据成员数组
- 如何使用基类的数据成员作为派生类的构造函数?(C++)
- 派生类没有额外的数据成员;将基对象静态向下转换为派生对象是否安全
- 如何访问充满派生类的矢量的数据成员
- C++是否可以从同级第二个派生对象访问第一个派生对象的受保护基础数据成员?
- 基础和派生类C 之间的继承数据成员
- VC++ 警告 C4356:无法通过派生类初始化静态数据成员
- 在派生类中使用提取运算符(>>)的方法以及在C++中处理静态数据成员的方法
- c++设计:从基类强制转换为派生类,没有额外的数据成员
- C++-填充派生类数据成员,同时设置基类属性值
- 仅授予派生类对基类数据成员/函数的 const 访问权限