2013-07-06 53 views
0

反正我可以通过类如下面的类传递参数。C++通过一个数组索引来传递参数/

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"); 
+2

我不明白你想要什么。换句话说,这对我来说没有意义。原样 – 2013-07-06 06:01:35

+0

你为什么将类和方法命名为相同的东西?这使得很难告诉你想要做什么。 – user2357112

+0

我想在传递索引数组的类中存储一个INT命名ID。 –

回答

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

此方法适用于任何数量的你想申报阵列。

1

可以使用静态变量,并增加它在构造函数中,保持所有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; 
} 
+0

你没有新的猫构造函数没有被调用... – ojblass

+0

我真的不知道这是如何工作,但我知道是非法的定义在类的int值是非法的。 –

+0

我认为它会工作......静态成员变量已被支持很长一段时间... – ojblass

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"); 
} 
+0

我会在一瞬间尝试,如果它生病会很开心。我明白你明白我的问题。 –

+0

不幸的是。 –

+0

试一下没有sizeof –