Reputation: 27
is there anyway I can pass a argument through a class like below for example.
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");
Upvotes: 0
Views: 418
Reputation: 33592
You can use static variable and increment it in constructor, to keep the track of all intances:
#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;
}
Upvotes: 1
Reputation: 9071
I tested this out and it worked well:
#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];
}
};
Now use it like this:
CatArray cats(18);
cats[1].dog("oh lol hi");
This method works for any number of arrays you'd wish to declare.
Upvotes: 1
Reputation: 21630
I am not entirely sure this will work but some variant of it might...
#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");
}
Upvotes: 0