【问题标题】:C++ header file with stack variable带有堆栈变量的 C++ 头文件
【发布时间】:2018-01-24 00:04:30
【问题描述】:

我最近开始学习 C++。

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

#ifndef DUMMY_H
#define DUMMY_H


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

};


#endif //DUMMY_H

【问题讨论】:

  • 要使用stack,编译器必须知道stack存在。 #include &lt;stack&gt;
  • 和顺便说一句 - 那不是定义变量。它定义了一个类。完全不同的事情

标签: c++ stack header-files


【解决方案1】:

你不见了:

  • #include &lt;stack&gt; 语句,因此编译器知道stack 是什么(以及std::pair#include &lt;utility&gt; 语句)。

  • using namespace std;using std::stack; 语句,因此您可以在不指定 std:: 前缀的情况下使用 std::stack

试试这个:

#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 一个类型/命名空间进入全局命名空间如果你不小心可能会导致不良副作用!

【讨论】:

    【解决方案2】:

    在使用它们之前,您必须包含必需的标题。 还必须注意添加适当的命名空间解析。

    #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 中需要额外的空格。 更多信息:Template within template: why "`>>' should be `> >' within a nested template argument list"

    这在 C++03 中不是必需的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-13
      • 1970-01-01
      • 1970-01-01
      • 2013-01-05
      • 1970-01-01
      • 2021-12-18
      • 1970-01-01
      • 2013-06-27
      相关资源
      最近更新 更多