0

无论如何,我可以通过如下所示的类传递参数。

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");
4

3 回答 3

1

您可以使用静态变量并在构造函数中递增它,以跟踪所有实例:

#include<iostream>


class cat
{
    int ID;
    static int IDTracker;
public:
    cat();
    void dog(char* value);
};

int cat::IDTracker = 0;
cat::cat()
{
    this->ID = cat::IDTracker;
    cat::IDTracker++;
}
void cat::dog(char *value)
{
    std::cout << value << this->ID;
}


int main()
{
    cat cats[18];
    cats[1].dog("Second instance, with index value: ");
    cats[2].dog("Third instance, with index vlaue: ");

    return 0;
}
于 2013-07-06T06:21:08.650 回答
1

我对此进行了测试,效果很好:

#include <vector>

// Forward declaration of the class
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.
        }
};

// Static variables need to be defined.
int Cat::ID = 0;

class CatArray {
    private:
        std::vector<Cat> cats;

    public:
        // explicit means that the argument passed to this constructor must 
        // be an unsigned int. The ": cats(size)" part is an initializer 
        // list that initializes the cats vector so that it would have the 
        // specified size.
        explicit CatArray(unsigned int size) : cats(size) {}

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

现在像这样使用它:

CatArray cats(18);

cats[1].dog("oh lol hi");

此方法适用于您希望声明的任意数量的数组。

于 2013-07-06T06:42:31.780 回答
0

我不完全确定这会起作用,但它的一些变体可能......

#include <stdio.h>
#include <stdlib.h>

void *foo;

class cat
{
  public:

  void dog(char *value) // int ID I'd like to be the index array it was called from?
  {
    int ID = (this - ((cat *)foo))/(sizeof(cat));
    printf("%d - %s",ID, value);
  }

};


int main ( void )
{
   cat cats[18];
   foo = &(cats);
   cats[1].dog("Fido");
}
于 2013-07-06T06:23:15.193 回答