【问题标题】:Why can't I access the private variables using an inheriting class? [duplicate]为什么我不能使用继承类访问私有变量? [复制]
【发布时间】:2018-09-04 07:28:44
【问题描述】:

我正在尝试继承某个类的一些私有成员。我不会放任何其他 cpp 文件或 .h 文件,因为这应该只涉及 BoxClass.h、Bullet.h 和 Bullet.cpp。在“Bullet::Bullet_Draw_Collision()”中的 bullet.cpp 中,程序无法从“BoxClass.h”中识别“ySize”。我继承了“BoxClass”类到“Bullet”类。为什么程序不能识别这个变量。谢谢!

编辑:为了简化我的问题,为什么我不能继承 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() {

};

【问题讨论】:

  • 你在问为什么 C++ 是这样设计的吗?
  • protected ...
  • @juanchopanza 不,我问的是为什么“Bullet_Draw_Collision()”中“Bullet.cpp”中的“ySize”变量不能从“BoxClass.h”访问。
  • @appleapple 受保护的继承不起作用。
  • 因为它是私有的。这就是“私人”这个词的作用。

标签: c++ visual-studio class inheritance visual-c++


【解决方案1】:

必须设置BoxClass protectedpublic 的成员才能在Bullet 中访问它们

BoxClass.h

class BoxClass 
{
protected: // or public, consider var access when designing the class
    int ySize;
};

子弹.h

class Bullet: private BoxClass // or protected or public
{
public:
    void Bullet_Draw_Collision();
};

子弹.cpp

void Bullet::Bullet_Draw_Collision() 
{
   // do whatever you need with inherited member vars
   ySize;
}

Bullet::Bullet() 
{
};

【讨论】:

    【解决方案2】:

    您可以使用这些选项中的任何一个。

    选项一:

     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);
    }
    

    【讨论】:

      猜你喜欢
      • 2014-09-09
      • 2016-12-12
      • 1970-01-01
      • 2017-12-01
      • 2016-07-30
      • 1970-01-01
      • 1970-01-01
      • 2015-02-03
      • 1970-01-01
      相关资源
      最近更新 更多