【问题标题】:C++ Pass a argument through a class with array index?C ++通过具有数组索引的类传递参数?
【发布时间】:2014-08-17 04:46:16
【问题描述】:
class cat
{public:
  void dog(int ID, char *value) // int ID I'd like to be the index array it was called from?
  {
    debug(ID, value);
  }
}

cat cats[18];

cats[1].dog("value second arg, first arg auto filled from index array");

我想要类似的东西。

   include <vector>

class CatArray;

class Cat {
    // This line means that the CatArray class can 
    // access the private members of this class.
    friend class CatArray;

    private:
        static int ID;

    public:
        void dog(const char* value) {
            // Use ID here any way you want.
        }
};

int Cat::ID = 0;

class CatArray {
    private:
        std::vector<Cat> cats;
    public:
        explicit CatArray(unsigned int size) : cats(size) {}

        Cat& operator [](unsigned int index) {
            Cat::ID = index;
            return cats[index];
        }
};

但有点不同。一个游戏中有 18 个客户端,我基本上需要这样做。例如,“客户端 4 选择一个选项,然后通过数组索引调用该选项,然后客户端 4 将调用具有索引 4 的函数的函数”

【问题讨论】:

  • 你的问题是......?
  • 我真的无法理解这一点;猫和狗的类比令人困惑(似乎您确实将“猫”和“狗”用作诸如“foo”和“bar”之类的无意义的词)。但我觉得你应该只使用std::map。即使地图不是正确使用的东西,原始数组和字符指针也肯定是错误的。

标签: c++ arrays class


【解决方案1】:

那么cats[1] 并不是真正的Cat 对象而是CatWithIndex 对象:

class Cat {
public:
  void dog(size_t index,const char* value);
};

class CatWithIndex {
  size_t index_;
  const Cat &cat_;
public:
  CatWithIndex(size_t index, const Cat &cat): index_(index), cat_(cat) {}

  void dog(const char* value) {
    cat_.dog(index_,value);
  }
};

class CatArray {
private:
    std::vector<Cat> cats;
public:
    Cat& operator [](unsigned int index) {
        Cat::ID = index;
        return CatWithIndex(index,cats[index]);
    }
};

【讨论】:

  • 我想知道游戏中有 2 名玩家,对吧?好吧,如果他们中的一个人打电话说 iprintin("Hello");// 只是在屏幕上打印文本,我想做到这一点。它只需要他们,而不是其他人
  • 那么我将传递什么作为客户端参数?会是 index_ 吗?
  • 类客户{私人:字节客户ID;公共:客户端(字节客户端){ ClientID = 客户端; } uint Entity(){return (0x82F03600 + (ClientID *0x280));} bool isAlive(){return *(PINT)((int)Entity() + 0x19F) ?真假; } };这是我目前的课程,不只是在做你知道吗?我基本上是在寻找它的“升级”哈哈
  • 抱歉无法理解您的 cmets。我不是以英语为母语的人。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-15
  • 2020-07-30
  • 2012-04-17
  • 2019-06-29
相关资源
最近更新 更多