【问题标题】:Hash table: How to use members declared in a header file in a different header file哈希表:如何在不同的头文件中使用在头文件中声明的成员
【发布时间】:2022-01-05 02:40:04
【问题描述】:

如果这是一个重复的问题,我深表歉意。我做了一些搜索,虽然他们中的大多数都提到在不同的 cpp 文件中使用类成员,但我没有找到任何关于头文件的询问。 main.cpp 确实插入了两个头文件。

我正在使用两个头文件,我们将它们称为 Acode 和 Bcode,分别具有 A 和 B 类。

Acode.h 头文件组成

template<typename X, typename Y>
class A{
public:
X key;
Y value;
bool isempty;
bool isremoved;

A<X,Y>(){
empty = true;
isremoved = false;
}

A<X,Y>(const X& input, const Y& input2){
key = input;
value = input2;
isempty = true;
isremoved = false;
}

Bcode.h 头文件使用 Acode.h 文件中的 A 类

template<typename X, typename Y>
class B{
public:
B(){
size = 80;
elem = 0;
table = new A<X,Y>[80];
};
//other unimportant functions

private:
int size, elem;
A<X,Y>* table; //this is the hash table 
//other unimportant variables

我希望能够使用在 Acode.h 的公共函数中声明的类成员。从这里开始,我知道我所做的一切都是错误的,但我不知道如何解决它。

class B{
//along with the codes mentioned above
public:
A<X,Y>* get_key(){
return key;
}

A<X,Y>* get_value(){
return value;
}

A<X,Y>* B<X,Y>::search(const X& key);

我尝试在不同的功能中使用这些,例如

A<X,Y>* B<X,Y>::search(const X& key){
int hashindex = hashfunction(key); //this is the hash function declared elsewhere in the code
if(table[hashindex].get_key() == key)
return table[hashindex].get_value();
}

我不断收到错误消息 错误:未在此范围内声明“键”; (连同价值) 错误:‘class B, int>’没有名为‘get_key’的成员

我正在尝试使用 A 类的成员,但似乎提到了评论者,我首先需要创建该类的实例?但我认为声明 A* 表就足够了。这个逻辑不正确吗? (我假设它可能是)。另外,由于 get_key 与 B 类型 int 没有关联,我该怎么做才能尝试解决这个问题?

编辑 我想通了,谢谢大家的帮助。

【问题讨论】:

  • 你需要创建一个对象的实例。它们不是头文件中的变量,它们是类的成员。如果你没有对象,你也没有任何变量。
  • 哦,我认为这更有意义。是的,我的意思是指他们有成员而不是变量,所以我为此道歉。
  • 请显示minimal reproducible example 并附上任何错误消息的全文
  • 我编辑了整个问题,试图使其更具可重复性和更深入。

标签: c++ data-structures hashtable header-files declaration


【解决方案1】:

是的,您可以在 B 类的成员函数中访问和设置 removedempty 的值。

但在 B 类中,您可以添加一个访问密钥的方法,如下所示。

X* get_key(){
return key;
}

【讨论】:

  • 哦,所以我不会将 get_key() 声明为 A* get_key() 而是 X* get_key()?你能再解释一下吗?非常感谢您的回复
  • 由于key的数据类型是'X',所以只有'X'作为返回类型就可以了。
猜你喜欢
  • 1970-01-01
  • 2014-04-07
  • 2010-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-13
  • 1970-01-01
  • 2015-02-13
相关资源
最近更新 更多