在类中声明数组并使用它

Declaring array in class and using it

本文关键字:数组 声明      更新时间:2023-10-16

我想在类hash中创建一个数组并在其方法中使用它。我尝试在public中声明它,但仍然其他方法无法访问它。这是我的类声明:

class hash
{   
    public:
    string hash_table[size]; //size is global variable;
    void initialize(int,string*,int); //I pass `hash_table` pointer and two other `int` type //arguments.
    int hash_function(string, int); 
    void quad_prob(int, int, string* , string); //`hash_table` array is used in this method also.
    void print(string*); //to print `hash_table` array
};

我只需要使用数组。另外,当我在int main()中使用hash h;时,请求可以解释一下会发生什么?这是完整的代码(不使用类结构 http://codepad.org/DQggdoI6):

看起来您正在尝试将现有代码转换为类,是吗? 在课堂上保持string hash_table[]私密。 然后从代码板上的每个函数中删除该参数。 所以initialize,正如人们所指出的,成为构造函数hash(int n, int size)并初始化hash_tablehash_table = new string[size]或类似的东西)。 类似地,print变成了普通print(),可以直接引用hash_table,因为它是hash类的成员函数。

当您

创建新的哈希对象时,您的数组将被初始化。您将在使用对象的任何代码之前使用哈希 h。创建新对象时,构造函数会设置对象以供以后在代码中使用。从那里你应该能够使用你的类中的代码。

首先,

我建议你使用一个向量。

其次,一旦在您的类中定义了它,您只需按名称访问它。

class foo
{
public: 
    foo(): vecfoo(5)
    {}
    void DoSomeThing()
    {
         for_each(begin(vecfoo),end(vecfoo),[](const string &){...});
    }
private:
    vector<string> vecfoo;

};