C++编写头文件(.h)时,定义了一个类,数据成员是两个栈的类型(就是用两个栈实现一个队列),我应该在哪个文件头部#include<stack>呢?

主函数main.cpp代码如下:

//main函数
#include <iostream>
//#include <stack>
#include "myQueue.h"
using namespace std; 

int main() {
    myQueue test;
    cout<<test.dele();
    cout<<endl;
    test.add(5);
    cout<<endl;
    test.add(2);
    cout<<endl;
    cout<<test.dele();
    cout<<endl;
    cout<<test.dele();
    cout<<endl;
    return 0;
}


myQueue.h代码:

//队列类头文件

//#include<stack>

#ifndef MY_QUEUE_H
#define MY_QUEUE_H

//#include<stack>

class myQueue {
    private:
        stack<int> tail;
        stack<int> head;
    public:
        void add(int);
        int dele();
};

#endif

两个成员函数的实现myQueue.cpp如下:

//队列类
#include<stack>
#include "myQueue.h"


void myQueue::add(int x) {
    tail.push(x);
}

int myQueue::dele() {
    int data;
    if(!head.empty()) {
        data=head.top();
        head.pop();
        return data;
    } 
    else {
        if(!tail.empty()) {
            while(!tail.empty()) {
                head.push(tail.top());
                tail.pop();
            }
            data=head.top();
            head.pop();
            return data;
        } 
        else {
            //cout<<"The queue is empty"<<endl;
            return -1;
        }
    }
}//end 

显示的报错信息:

img

我尝试在这三个文件中都#include过,但是还是出错。

哪里用到,就在哪里#include
根据上述代码,应该在myQueue.h
用#include "stack.h"

原则是:在哪里用到了stack,头文件就放在哪里,如果你在类中用到了,就放在类文件中