Error `no nombra un tipo` con `namespace std;` y archivos
Frecuentes
Visto 30,332 veces
2
compiling the code below with g++ main.cpp functions.cpp -o run
me da el error error: ‘vector’ does not name a type
. Declaring namespace at the top of main.cpp
usually works across all .cpp
archivos para mí.
main.cpp
using namespace std;
#include "functions.h"
main () {}
funciones.h
#include <vector>
funciones.cpp
#include "functions.h"
vector <int> x;
EDIT: I appreciate the fact all responders know what their talking about, but this normally works for me. Would the use of a makefile have any bearing on that? something else that I might be missing?
4 Respuestas
10
Yes but in this example functions.cpp
no ha visto using namespace std
since you only wrote that in main.cpp
.
No agregue using namespace std
a functions.h
, Utilizar std::
to qualify types. Adding a using..
imposes an unnecessary burden on the user of your header.
Respondido 28 ago 12, 12:08
8
You need to qualify the namespace:
#include "functions.h"
std::vector<int> x;
Tiene using namespace std
in main.cpp
, and it cannot be seen by functions.cpp
. That is the root of the problem.
En general, debes evitar using namespace std
, specially in headers. And if you really must include it in main
, put it after all the headers.
Respondido 28 ago 12, 12:08
3
Importaste el std
namespace only in main.cpp
, no en functions.cpp
.
You have to qualify your use - std::vector
in the second file, or use the using
directiva:
//functions.cpp
#include "functions.h"
std::vector <int> x; // preferred
or
//functions.cpp
#include "functions.h"
using namespace std;
vector <int> x;
or (bonus)
//functions.cpp
#include "functions.h"
using std::vector;
vector <int> x;
Declaring namespace at the top of main.cpp usually works across all .cpp files for me.
You have a really flawed compiler then. using
directives shouldn't influence translation units that don't have direct visibility over the directive.
Respondido 28 ago 12, 12:08
1
Usted using namespace std
is local to main.cpp only. You need to use
std::vector<int> x;
in your source file functions.cpp
Respondido 28 ago 12, 12:08
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas c++ header namespaces or haz tu propia pregunta.
I will change downvote to an upvote for anyone who adresses the fact that this usually works for me. Even your answers is only speculative. - matt munson
@MattMunson it cannot possibly work for you (in this particular case), because
using namespace std
is not seen infunctions.cpp
. And assuming thatusing namespace std
can be seen somewhere can only lead to trouble. - juanchopanza