我正在尝试将字符串输入(数学方程(存储到队列链表中。要将字符添加到队列中,我需要访问Queue函数";排队((";从一个单独的类内部:;计算";班
我不断收到错误消息("队列":未声明的标识符(和("QueObj":未宣布的标识符(。
我的代码大部分看起来是这样的(删除了大多数不相关的代码(:
#include <iostream>
#include <stdlib.h>
#include <string>
class Calculate // Convert from string to node
{
public:
double Calc(string text)
{
input = text; // math notation, user input sent from main()
/* error message here -> */ Queue queObj; // Queue object created to access Queue functions
/* error message here -> */ queObj.Enqueue(text); // Enqueues the notation into a Queue
};
private:
string input; // The input string for the math equation
};
class Queue
{
public:
void Enqueue(string queVal) // Enqueue definitions
{
// Enqueue instructions
};
void Dequeue() // Dequeue definitions
{
// Dequeue instructions
};
bool IsEmpty() // Queue size check
{
// Queue size check
};
private:
Node *head = NULL; // Pointer for start of queue (set to NULL)
Node *tail = NULL; // Pointer for end of queue (set to NULL)
friend class Calculate; // Friend class allows Calculate to access Queue private data
};
int main()
{
string Eq1 = "1 + 2"; // math equation
Calculate calcObj; // object to access calculate class functions and variables
calcObj.Calc(Eq1); // stores the equation into calculate class
return 0;
}
简单地说,类Queue
对类Calculate
不可见,因为编译器(粗略地说(以自上而下的方式读取和编译代码。因此,编译器在解析类Calculate
的内容时不知道存在一个名为Queue
的类。
有两种方法可以做到这一点:
- 将类声明放在所有类定义的顶部。类声明如下所示:
class Queue
{
public:
void Enqueue(string queVal); // Enqueue definitions
void Dequeue(); // Dequeue definitions
bool IsEmpty(); // Queue size check
private:
Node *head = NULL; // Pointer for start of queue (set to NULL)
Node *tail = NULL; // Pointer for end of queue (set to NULL)
friend class Calculate; // Friend class allows Calculate to access Queue private data
};
然后在底部,您可以定义以下所有功能:
void Queue::Enqueue(string queval)
{
// Enqueue instructions
}
// rest of the functions
- 创建一个包含所有此类声明的头文件,然后包含该头文件。然后创建一个包含所有函数定义的
.cpp
文件。在编译程序时,链接两个对象文件(推荐选项,因为它不那么杂乱,而且易于扩展(
此外,与这里的问题无关,但理想情况下应该明确提及main
的返回类型,如下所示
int main()
由于没有明确提及main
的返回类型,此代码甚至可能不会在较新的C++标准下编译。
此外,您不需要在函数定义后使用分号(;
(。
最后,正确格式化代码(特别是不要使用不一致的缩进(。