我试图使用两个类的变量,以便可以从A类的变量访问B类的变量,反之亦然。但是,我找不到可行的解决方案。它总是以循环或以下错误结尾:

error: invalid use of non-static data member

这是代码示例:

Player.h:
  #ifndef _PLAYER_H_
  #define _PLAYER_H_

#include "Segment/Dynamic_Segment.h"

class Attributes_P;

class Attributes_P : public Attributes_DS{
  protected:
  int inv_mcols, inv_mrows;

  public:
  Attributes_P();
  void controls( int MKEY_UP, int MKEY_RIGHT, int MKEY_DOWN, int MKEY_LEFT );
  void inventory( int inv_mcols, int inv_mrows );
};

class Player : public Dynamic_Segment{
  protected:
  int   **inv;

  public:

  int   MKEY_UP, MKEY_RIGHT, MKEY_DOWN, MKEY_LEFT;

  public:

  Player();
  Attributes_P set;
  friend class Core;
  friend class Attributes_P;

};
#endif

Player.cpp:
#include "Segment/Player.h"

Attributes_P::Attributes_P(){};

Player::Player() : Dynamic_Segment(){
  set.inv_mcols = 0;
  set.inv_mrows = 0;
}

void Attributes_P::inventory( int inv_mcols, int inv_mrows ) {
  this->inv_mcols = inv_mcols;
  this->inv_mrows = inv_mrows;
  Player::inv = new int*[this->inv_mcols]; //<--- Error here
  for( int i = 0; i < this->inv_mrows; i++ ) {
    Player::inv[i] = new int[this->inv_mcols]; //<--- Error here
  }
}

void Attributes_P::controls( int MKEY_UP, int MKEY_RIGHT, int MKEY_DOWN, int MKEY_LEFT ) {
  Player::MKEY_UP = MKEY_UP; //<--- Error here
  Player::MKEY_RIGHT = MKEY_RIGHT; //<--- Error here
  Player::MKEY_DOWN = MKEY_DOWN; //<--- Error here
  Player::MKEY_LEFT = MKEY_LEFT; //<--- Error here
}

现在已经将我的头撞在墙上有一段时间了...任何想法都将不胜感激!

最佳答案

您无法访问属性MKEY_UP,MKEY_RIGHT,MKEY_DOWN,MKEY_LEFT和inv,因为它们是私有(private)的。

将它们设为私有(private)并编写getter / setter!

关于c++ - C++类纠缠,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14281429/

10-11 15:11