为什么我无法使用继承类访问私有变量?

Why can't I access the private variables using an inheriting class?

本文关键字:访问 变量 继承 为什么      更新时间:2023-10-16

我正在尝试继承类的一些私人成员。我不会放置任何其他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 protectedpublic的成员,以便在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);
}