为什么我无法使用继承类访问私有变量?
Why can't I access the private variables using an inheriting class?
我正在尝试继承类的一些私人成员。我不会放置任何其他CPP文件或.H文件,因为这只能关注BoxClass.h,bullet.h和bullet.cpp。在" bullet :: bullet_draw_collision(("的" bullet.cpp"中,这些程序未从" boxclass.h"中识别" ysize"。我将" BoxClass"类继承为"子弹"类。为什么该程序不识别此变量。谢谢!
编辑:为了简化我的问题,为什么我不能继承ysize变量。
boxclass.h:
#ifndef BOXCLASS_H
#define BOXCLASS_H
class BoxClass {
//prv variables
unsigned short int width, retrieveX;
int height, i, xSize, ySize, rightWall;
float space_Value, height_Count;
bool error;
int width_Var, height_Var, position_Var;
int speed_Var = 1;
unsigned short int horizontalCount = 0, verticleCount = 0;
public:
int Retrieve_X();
void Print_Rectangle_Moving(int x, int y, int horizontalSpaces, int verticleSpaces);
void Print_Solid_Rectangle();
void Rectangle_Movement(int speed);
//function shows area of individual spaces
float Rectangle_Area();
// constructor
BoxClass(int x, int y);
};
#endif
bullet.h:
#ifndef BULLET_H
#define BULLET_H
class Bullet: private BoxClass{
public:
void Bullet_Draw_Collision();
//constructor
Bullet();
};
#endif
bullet.cpp:
#include "BoxClass.h"
void Bullet::Bullet_Draw_Collision() {
ySize;
}
Bullet::Bullet() {
};
you 必须设置BoxClass
protected
或public
的成员,以便在Bullet
boxclass.h
class BoxClass
{
protected: // or public, consider var access when designing the class
int ySize;
};
子弹
class Bullet: private BoxClass // or protected or public
{
public:
void Bullet_Draw_Collision();
};
bullet.cpp
void Bullet::Bullet_Draw_Collision()
{
// do whatever you need with inherited member vars
ySize;
}
Bullet::Bullet()
{
};
您可以使用以下任何一个选项。
选项1:
class BoxClass {
protected:
int ySize;
};
选项2:
class BoxClass {
private:
int ySize;
protected:
//properties
void set_ysize(int y);
int get_ysize() const;
};
void Bullet::Bullet_Draw_Collision()
{
set_ysize(10);
}
相关文章:
- 尝试通过多个向量访问变量时,向量下标超出范围
- 通过按地址访问变量
- 通过 get-Method 访问变量在类外不起作用
- 是否可以使用指针访问变量以避免直接编辑变量?
- 我无法访问变量的值,即使我通过范围传递了它
- 简单的问题 - 如何从单独的"结构"内的'class'访问变量?
- (C++) 从另一个类访问变量时值无效
- 返回实例变量的c++方法可以访问变量中的数据,但不能更改它,但在编译时不会生成错误
- 是否可以从字符串访问变量?
- 变量 z 无法从其他函数访问变量 x
- 如何在 C++ 中从 void 返回函数访问变量
- 在链接的程序集文件中,我想从 c++ 调用代码访问变量.是否可以在不触发访问冲突的情况下执行此操作?
- 在C 中本地声明隐藏的封闭范围(而非全局)中访问变量
- 从函数中删除动态内存分配,但无法访问变量
- 如何从派生类中的基类访问变量的值?
- 如何通过指针更快地访问变量,然后直接访问变量?
- 如何在公共类 c++ 中访问变量的值
- 从 Visual Studio 中的多个源文件访问变量
- 使用命名空间和模板类访问变量
- 从子对话框访问变量