在类中声明数组并使用它
Declaring array in class and using it
我想在类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_table
(hash_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;
};
相关文章:
- 无法将字符串数组声明为类成员而不是字符 (C++)
- 为什么从函数返回数组时需要将数组声明为静态数组.(C++)
- 在 c++ 中直接访问的内联数组声明
- 由于 2D 数组声明,C++ 14 中的运行时错误
- 如何将char数组声明为函数参数?或告诉我此代码中还有其他问题?
- 来自函数参数的 C++ 静态数组声明
- C++ 中的动态数组声明
- C++数组声明
- 数组声明中的错误:表达式必须具有常量值
- 程序随数组声明崩溃
- 运行时和编译时的数组声明
- C++数组声明和初始化
- 带有常量表达式的数组声明
- C ,数组声明,模板,链接器错误
- 如何用'n'维数组声明 std::vector?
- 数组声明上的编译器错误
- 这是什么数组声明
- 头文件类中的数组声明
- 节点数组声明
- 在静态数组声明中使用了两次C++常量