带有堆栈变量的 C++ 头文件

C++ header file with stack variable

我最近开始学习C++。

我想知道为什么不能像这样在头文件中定义变量:

#ifndef DUMMY_H
#define DUMMY_H


class Dummy
{
stack<std::pair<int, int>> s;   

};


#endif //DUMMY_H

您还缺少:

  • a #include <stack> 语句,因此编译器知道 stack 是什么(以及 std::pair#include <utility> 语句)。

  • a using namespace std;using std::stack; 语句,因此您可以使用 std::stack 而无需指定 std:: 前缀。

试试这个:

#ifndef DUMMY_H
#define DUMMY_H

#include <stack>
#include <utility>

using std::stack;

class Dummy
{
    stack<std::pair<int, int>> s;   
};

#endif //DUMMY_H

你真的不应该在头文件 * 中使用 using 语句,除非它嵌套在显式命名空间中:

#ifndef DUMMY_H
#define DUMMY_H

#include <stack>
#include <utility>

class Dummy
{
    std::stack<std::pair<int, int>> s;   
};

#endif //DUMMY_H

* using 将 type/namespace 放入全局命名空间中,如果不小心,可能会导致不良副作用!

您必须在使用前包含必需的 header。 还必须注意添加适当的名称space 解析。

#ifndef DUMMY_H
#define DUMMY_H

#include <stack>
#include <utility>  // This has added for pair

class Dummy
{
    std::stack<std::pair<int, int> > s;  // Notice the space between > >.
};

#endif //DUMMY_H

出于语法原因,在早期版本的 C++98 中需要额外的 space。 更多信息:Template within template: why "`>>' should be `> >' within a nested template argument list"

这不是 C++03 所要求的