【问题标题】:C++ Pass a argument through a class with array indexC ++通过具有数组索引的类传递参数
【发布时间】:2014-07-31 00:52:33
【问题描述】:

我是否可以通过下面的类传递参数。

class cat
{
public:
    void dog(int ID, const 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");

【问题讨论】:

  • 既然您仍然指定索引 (cats[1]),是什么阻止您在方法调用中再次这样做?您是否打算像指针 cat *p = cats; p->dog(...); 一样行走并以某种方式推断索引?
  • 我不想那样做,我想基本上在那里有一个变量,将它存储在数组中,例如。有 18 个客户端,如果有人调用该选项,我想将其存储在数组中的 clientIndex 编号
  • 为什么在cat 中没有成员ID(在构造时只填写一次),然后在所有其他方法中避免它?
  • 告诉我你会怎么做,因为我想我知道你在说什么,但我想确定
  • @HorseFrog 啊,我明白了,正如你所写的,包含的序列是不相交的。 cats 数组中的 cats 与位置无关,这是理所当然的。如果没有每个实例中包含的属性或用于访问的无包装函数,这是不可能的。

标签: c++ class parameter-passing


【解决方案1】:

这样的事情怎么样:

class cat
{
public:
    void dog(const char *value)
    {
        //debug(ID, value);
    }
};

cat cats[18];

void cat_dog(int ID, const char *value)
{
    debug(ID, value);
    cats[ID].dog(value);
}

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

【讨论】:

  • 例如。一个叫布拉德 14 的人。他加入了游戏,他的客户端索引号是 13,这是由服务器选择的,所以基本上我希望他调用的函数获取他的客户端索引号并将其存储在数组中。因此服务器给出的客户端客户端索引号存储在数组中。
  • 我认为您最好编辑您的问题以明确说明您想要做什么。
【解决方案2】:

正如评论中提到的,您也可以使用成员来存储索引,然后无需在连续调用中提供它:

class cat
{
public:
    cat(int index) : index(index) {}

    void dog(const char *value) { debug(index, value); }

private:
    std::size_t index;
};

然后初始化数组:

std::vector<cat> cats;

for (std::size_t i = 0; i != 18; ++i) {
    cats.push_back(cat(i));
}

然后调用任意方法:

cats[1].dog("text value, index 1 already stored in object");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-15
    • 2020-07-30
    • 2012-04-17
    • 2019-06-29
    相关资源
    最近更新 更多