在另一个类中使用类函数

时间:2014-06-06 15:21:23

标签: c++ class linked-list stack header-files

我有一个完美运行的LinkedList.h头文件。我试图使用LinkedList来实现堆栈。问题在于使用此MyStack类中LinkedList类的函数。 InsertFront(key)是LinkedList类中的一个函数。现在,当我运行它时,我得到以下2个错误。

'list':未声明的标识符

'.InsertFront'左边的

必须有class / struct / union

这两个都引用了以下代码的最后一行:

#include "LinkedList.h"
#include <iostream>
using namespace std;



class MyStack
{
    private:
    //LinkedList list;


    public:
        //Implement the following functions whose purpose should be obvious
        MyStack();
        ~MyStack();
        void Push(int key);
        int Pop();
        bool isEmpty();
        int Size();
        void Display(); // Just show the elements from top of stack to the bottom without removing them
        int Top(); // Return the element at the top of the stack without removing it
};


MyStack::MyStack()
{
    LinkedList list;
}

MyStack::~MyStack()
{

}

void MyStack::Push(int key)
{

    list.InsertFront(key);
}

cpp文件如下:

#include "MyStack.h"
#include <iostream>
using namespace std;

int main()
{
    MyStack s;
    int value, choice;
    do{
        cout << "Enter 1 to push,\n2 to pop,\n3 to display the contents of the stack,\n4 to display the item at the top of the stack,\n5 to find the size of the queue,\n0 to quit"<<endl;
        cin >> choice;
        switch(choice)
        {
            case 1:
                cout << "Key: ";
                cin >> value;
                s.Push(value);
                break;
            case 2:
                cout << "The item removed from the top of the stack is: " << s.Pop() << endl;
                break;
            case 3:
                s.Display();
                break;
            case 4: 
                cout << "The item at the top of the stack is: " << s.Top() << endl;
                break;
            case 5: 
                cout << "The size of the stack is: " << s.Size() << endl;;
            case 0:
                break;
        }
    } while (choice != 0);
    return 0;
}

1 个答案:

答案 0 :(得分:6)

您注释掉了LinkedList的声明,而是将其作为构造函数的局部变量。当完成构造函数后,类的其余部分在超出范围时应该如何知道LinkedList list