I recently started learning C++.
I would like to know why it is not possible to define a variable in a header file like this :
#ifndef DUMMY_H
#define DUMMY_H
class Dummy
{
stack<std::pair<int, int>> s;
};
#endif //DUMMY_H
I recently started learning C++.
I would like to know why it is not possible to define a variable in a header file like this :
#ifndef DUMMY_H
#define DUMMY_H
class Dummy
{
stack<std::pair<int, int>> s;
};
#endif //DUMMY_H
You are missing:
a #include <stack>
statement, so the compiler knows what stack
is (and a #include <utility>
statement for std::pair
).
a using namespace std;
or using std::stack;
statement, so you can use std::stack
without specifying the std::
prefix.
Try this:
#ifndef DUMMY_H
#define DUMMY_H
#include <stack>
#include <utility>
using std::stack;
class Dummy
{
stack<std::pair<int, int>> s;
};
#endif //DUMMY_H
You really shouldn't use a using
statement in a header file *, unless it is nested inside of an explicit namespace:
#ifndef DUMMY_H
#define DUMMY_H
#include <stack>
#include <utility>
class Dummy
{
std::stack<std::pair<int, int>> s;
};
#endif //DUMMY_H
* using
a type/namespace into the global namespace can cause undesirable side effects if you are not careful!
You must include required header before using them. Also precaution has to be taken care to add appropriate namespace resolution.
#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
Additional space is required in earlier version of C++98 for grammatical reason. More information: Template within template: why "`>>' should be `> >' within a nested template argument list"
This is not required from C++03