私有成员函数中对非静态成员的非法引用
我正在尝试编写一个程序,但我不明白为什么我的私有成员函数无法访问我的私有数据成员。有人愿意帮忙吗?这是我的功能。 nStocks、capacity 和 slot[] 都是私有数据成员,hashStr() 是私有函数。
bool search(char * symbol)
{
if (nStocks == 0)
return false;
int chain = 1;
bool found = false;
unsigned int index = hashStr(symbol) % capacity;
if (strcmp(symbol, slots[index].slotStock.symbol) != 0)
{
int start = index;
index ++;
index = index % capacity;
while (!found && start != index)
{
if(symbol == slots[index].slotStock.symbol)
{
found = true;
}
else
{
index = index % capacity;
index++;
chain++;
}
}
if (start == index)
return false;
}
return true;
}
这是我的 .h 文件的私有成员部分:
private:
static unsigned int hashStr(char const * const symbol); // hashing function
bool search(char * symbol);
struct Slot
{
bool occupied;
Stock slotStock;
};
Slot *slots; // array of instances of slot
int capacity; // number of slots in array
int nStocks; // current number of stocks stored in hash table
如果我可以提供任何其他信息,请告诉我。
I'm trying to write a program, but I can't figure out why my private member function can't access my private data members. Will somebody please help? Here's my function. nStocks, capacity, and slots[] are all private data members, and hashStr() is a private function.
bool search(char * symbol)
{
if (nStocks == 0)
return false;
int chain = 1;
bool found = false;
unsigned int index = hashStr(symbol) % capacity;
if (strcmp(symbol, slots[index].slotStock.symbol) != 0)
{
int start = index;
index ++;
index = index % capacity;
while (!found && start != index)
{
if(symbol == slots[index].slotStock.symbol)
{
found = true;
}
else
{
index = index % capacity;
index++;
chain++;
}
}
if (start == index)
return false;
}
return true;
}
Here is the private members section of my .h file:
private:
static unsigned int hashStr(char const * const symbol); // hashing function
bool search(char * symbol);
struct Slot
{
bool occupied;
Stock slotStock;
};
Slot *slots; // array of instances of slot
int capacity; // number of slots in array
int nStocks; // current number of stocks stored in hash table
Please let me know if I can provide any additional information.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的代码创建一个名为
search
的非成员函数。您需要更改:至:
将
ClassName
替换为类的名称。Your code creates a non-member function called
search
. You need to change:To:
Replace
ClassName
with the name of the class.你的功能是静态的,这就是原因。静态函数只能访问类的静态成员。
编辑:实际上你必须澄清你的问题,因为其他答案也可能是正确的......
You function is static, that's why. Static functions can have access to static members of the class only.
EDIT: Actually you must clarify your question as the other answer can be also correct...