|
AKE 12 / 12 / 3 Регистрация: 09.05.2010 Сообщений: 384 |
||||
|
1 |
||||
|
14.05.2010, 00:16. Показов 28487. Ответов 17 Метки нет (Все метки)
error C2871: ‘std’ : does not exist or is not a namespace Microsoft VC++ 6.0
__________________
0 |
|
бжни 2473 / 1684 / 135 Регистрация: 14.05.2009 Сообщений: 7,162 |
|
|
14.05.2010, 00:24 |
2 |
|
вы должные включить заголовки, которые чтонибудь туда добавят, например #include <vector> #include <iostream>
0 |
|
12 / 12 / 3 Регистрация: 09.05.2010 Сообщений: 384 |
|
|
14.05.2010, 00:27 [ТС] |
3 |
|
alex_x_x
0 |
|
229 / 67 / 11 Регистрация: 02.06.2009 Сообщений: 280 |
|
|
14.05.2010, 12:35 |
4 |
|
.h убери в iostream
0 |
|
8376 / 3598 / 419 Регистрация: 03.07.2009 Сообщений: 10,708 |
|
|
14.05.2010, 21:22 |
5 |
|
AKE, в зависимости от того как вы создавали проект, вам может не понадобится std;
0 |
|
21259 / 8275 / 637 Регистрация: 30.03.2009 Сообщений: 22,634 Записей в блоге: 30 |
|
|
15.05.2010, 08:47 |
6 |
|
error C2871: ‘std’ : does not exist or is not a namespace namespace std появилось только в более поздних версиях стандарта Си++ и предназначен для того, чтобы втащить в него всё то, что описано в стандарте Си++ (чтобы проще было отделять мух от котлет). А в старых версиях стандарта (и, соответственно, в старых версиях компиляторах) этого namespace’а не было вообще. К тому же раньше все заголовочные файлы от стандартных библиотек Си++ имели расширение .h: т.е. нужно было писать, например, #include <iostream.h>. В новых стандартах вся стандартная поддержка языка Си++ описана в заголовочных файлах без расширений: т.е. теперь надо писать #include <iostream>, но потом добавлять using namespace std; (либо ко всем глобалам обращаться через std, типа std::cout). Большинство современных компиляторов для совместимости поддерживают в том числе и старый вариант. Но в старых компиляторах нового варианта нет (потому что в те времена его ещё не изобрели). Поэтому в твоём случае нужно просто удалить строку «using namespace std;» (поскольку ты использовал файл с расширением .h). Либо все подключаемые файлы стандартной библиотеки Си++ должны быть без .h (в твоём случае вместо iostream.h должно быть iostream)
2 |
|
Заблокирован
|
|
|
05.01.2012, 23:17 |
7 |
|
Evg, чисто для себя хочу узнать — здесь на форуме часто вижу std::cout и т.д.(и все с пеной у рта утверждают что без std:: не по стандарту)
0 |
|
3211 / 1459 / 73 Регистрация: 09.08.2009 Сообщений: 3,441 Записей в блоге: 2 |
|
|
05.01.2012, 23:37 |
8 |
|
-=ЮрА=-, раскрытие пространства имен, весьма опасная привычка. это годится для хеловордов, или же для программ не использующих ничего кроме стандартной библиотеки.
0 |
|
21259 / 8275 / 637 Регистрация: 30.03.2009 Сообщений: 22,634 Записей в блоге: 30 |
|
|
06.01.2012, 00:28 |
9 |
|
-=ЮрА=-, ну, например, ты можешь написать проект с 100500 функциями и называть их «a», «b», «c», … — это будет по стандарту, но затруднит тебе жизнь. С std:: то же самое. Если это «домашняя» программа на два экрана — то проще using использовать, в противном случае лучше std::. Да и вообще лучше заранее приучать себя к тому, что является «правильным» в случаях, когда большой проект пишут несколько людей
1 |
|
Gepar 1186 / 542 / 78 Регистрация: 01.07.2009 Сообщений: 3,517 |
||||||||
|
06.01.2012, 00:45 |
10 |
|||||||
|
AKE, дело в том что написав
в вашем случае пользы не принесёт, проект и с ней должен нормально компилироваться, что и происходит в minigw, но почему-то не происходит в vs 6.0 (сам вот тоже проверил из интереса).
то тогда конфликтов у vs с пространствами имён не возникает так что либо пишите так либо не пишите using namespace std раз уж таким образом подключили нужные вам библиотеки.
0 |
|
21259 / 8275 / 637 Регистрация: 30.03.2009 Сообщений: 22,634 Записей в блоге: 30 |
|
|
06.01.2012, 01:01 |
11 |
|
Для полноты картину ещё и сюда ссылку закину: include <?> для cout
0 |
|
бжни 2473 / 1684 / 135 Регистрация: 14.05.2009 Сообщений: 7,162 |
|
|
09.01.2012, 14:52 |
12 |
|
вообще это вопрос холивара, а не языка
0 |
|
0 / 0 / 0 Регистрация: 26.09.2012 Сообщений: 38 |
|
|
11.11.2012, 23:38 |
13 |
|
-=ЮрА=-, ну, например, ты можешь написать проект с 100500 функциями и называть их «a», «b», «c», … — это будет по стандарту, но затруднит тебе жизнь. С std:: то же самое. Если это «домашняя» программа на два экрана — то проще using использовать, в противном случае лучше std::. Да и вообще лучше заранее приучать себя к тому, что является «правильным» в случаях, когда большой проект пишут несколько людей Можно пример (желательно для новичка) в котором using namespace std; может повредить программе ?
0 |
|
бжни 2473 / 1684 / 135 Регистрация: 14.05.2009 Сообщений: 7,162 |
|
|
11.11.2012, 23:56 |
14 |
|
Можно пример (желательно для новичка) в котором using namespace std; может повредить программе ? LinkedList list;
0 |
|
Croessmah Don’t worry, be happy 17777 / 10542 / 2034 Регистрация: 27.09.2012 Сообщений: 26,510 Записей в блоге: 1 |
||||
|
12.11.2012, 00:01 |
15 |
|||
|
может повредить программе ? как вариант:
0 |
|
0 / 0 / 0 Регистрация: 26.09.2012 Сообщений: 38 |
|
|
12.11.2012, 00:53 |
16 |
|
CroessmahПоясните, что здесь не верно ? К nothrow будет применяться std ?
0 |
|
424 / 389 / 113 Регистрация: 21.09.2012 Сообщений: 913 |
|
|
12.11.2012, 01:07 |
17 |
|
Переменная nothrow уже есть в std:: const std::nothrow_t std::nothrow Миниатюры
0 |
|
0 / 0 / 0 Регистрация: 26.09.2012 Сообщений: 38 |
|
|
12.11.2012, 01:10 |
18 |
|
Благодарю за пояснение.
0 |
- Forum
- General C++ Programming
- error with using namespace std
error with using namespace std
the program runs well for this header file.
#pragma once
#include»birthday.h»
#include<string>
using namespace std;
class people
{
public:
people(string yourName, birthday DOB);
void printInfo();
private:
string name;
birthday dobObject;
};
but
by removing using namespace std; the programs fails with error. can you please give me the reason and elaborate?
#pragma once
#include»birthday.h»
#include<string>
class people
{
public:
people(string yourName, birthday DOB);
void printInfo();
private:
string name;
birthday dobObject;
};
Last edited on
1. Avoid
using namespace std;
at global scope in a header file.
2. In the header, use qualified names for entities from the standard library
|
|
#pragma once
class birthday
{
public:
birthday(int m, int d , int );
void printOutDOB();
private:
int day;
int month;
int year;
};
excuse me sir, but for above header file «bithday.h» i didn’t have to use qualified names for int. is there some rules for that in documentation or what? can you elaborate it?
1) Please use code tags when posting code, to make it readable:
http://www.cplusplus.com/articles/z13hAqkS/
2) There’s nothing in the header file that needs a std:: qualification, but there are things in your source file. Since there’s no longer a using namespace std; statement anywhere in the translation unit, you’ll need to qualify those names in the source file.
Last edited on
by removing using namespace std; the programs fails with error.
You do mean that the compiler aborts and gives error messages.
It is not enough to merely note that there is «an error». You have to read the error messages carefully, because they tell what offends the compiler.
For example,
|
|
Produces on one compiler:
6:24: error: expected ')' before 'yourName' 11:9: error: 'string' does not name a type
and in another:
main.cpp:6:24: error: expected ')' before 'yourName'
people( string yourName, int DOB );
^
main.cpp:11:9: error: 'string' does not name a type
string name;
^
Both clearly point to lines 6 and 11.
Line 11 is quite clear; the compiler understands that ‘string’ should probably be a name of a type, but compiler has not seen definition of such type. You do include <string> and it does contain definition of ‘string’, but that definition is within namespace ‘std’ and the compiler does not see inside namespaces unless it is told to look there.
Both using namespace std; and using std::string; essentially state that when looking for ‘string’, a ‘string’ inside ‘std’ is a match too.
std::string in code is more explicit: only the ‘string’ in ‘std’ is a match.
What is before ‘yourName’ on line 6? people( string
This message is harder to explain.
We can try to humor the compiler and test what happens if we write line 6 as:
people( string );
Alas, that gives a different error:
6:24: error: field 'string' has incomplete type 'people'
The important thing is to read those error messages and use the info the best you can.
For example, when asking for help do show the exact messages. Someone might be able to help you read them.
clang++ emits a very clear diagnostic.
MinGW64 6:38am /r/code/test >CC --version
clang version 5.0.1 (tags/RELEASE_501/final)
Target: x86_64-w64-windows-gnu
Thread model: posix
InstalledDir: C:msys64mingw64bin
MinGW64 6:38am /r/code/test >CC -c test.cpp
test.cpp:6:17: error: unknown type name 'string'; did you mean 'std::string'?
people( string yourName, int DOB );
^~~~~~
std::string
C:msys64mingw64includec++7.3.0bits/stringfwd.h:74:33: note: 'std::string' declared here
typedef basic_string<char> string;
^
test.cpp:11:9: error: unknown type name 'string'; did you mean 'std::string'?
string name;
^~~~~~
std::string
C:msys64mingw64includec++7.3.0bits/stringfwd.h:74:33: note: 'std::string' declared here
typedef basic_string<char> string;
^
2 errors generated.
Topic archived. No new replies allowed.
- Remove From My Forums
-
Question
-
hi,
i am writing a program containing serial port communication , for a customized hand held device, with the help of embedded VC++ 3.0. while compiling the module for the serial port , i am getting the following errors.
error C2871: ‘std’ : does not exist or is not a namespace
error C2065: ‘cout’ : undeclared identifier
error C2297: ‘<<‘ : illegal, right operand has type ‘unsigned short [200]’my code contains the following lines…
#include<iostream>
#include «stdafx.h»
#include «serial.h»#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
using namespace std;
HANDLE hCommPort = INVALID_HANDLE_VALUE;
void CSerial::ConfigPort()
{
…..
…
cout<< _T(«Com. port closed»)<<endl;
….
….
kindly help me to solve this problem.thank you
Geo Babu
Answers
-
Hi Geo,
If you’re using precompiled headers the compiler will ignore anything above:
Code Snippet
#include «stdafx.h»
You need to move your include to <iostream> below this line or put it inside stdafx.h.
John.
Welcome to the boards. If you haven’t already done so then please take some time to familiarise yourself with the faq:
http://faq.cprogramming.com/cgi-bin/smartfaq.cgiMake sure you have a look at the the posting guidelines:
http://cboard.cprogramming.com/annou…ouncementid=51
Following the rules will ensure you get a prompt answer to your question.Remember, too, that the board has a search facility, a link is at the top of your screen:
http://cboard.cprogramming.com/search.php
It will often get you a quicker answer to your questions than waiting for a response to one you have posted.If you have any questions about this you may ask or you can contact one of our forum leaders:
http://cboard.cprogramming.com/showgroups.php
———————————————
In this case, it looks like you were able to search for a similar problem, but it would be better to start a new thread and link to the one you find rather than bumping the old thread.
Borland 5.02 appears to be a very old compiler that probably doesn’t support modern, standard C++ (and in this case namespaces). Consider using a different compiler. There are several free IDEs available that come with good modern compilers (e.g. VC++ Express, Dev-C++, Code::Blocks).
|
|
|
|

Правила раздела Visual C++ / MFC / WTL (далее Раздела)

Компилятор не видит пространство имён std
- Подписаться на тему
- Сообщить другу
- Скачать/распечатать тему
|
|
|
|
переустанавливал windows => пришлось переустановить Visual Studio 2008 Express Edition. Цитата error C2653: std: не является именем класса или пространства имен самое интересное, что когда в компиляторе ввожу std:: ,то вылазит окошечко со всем содержимым namespace’a.
std::wstring str1; class blalabadsf { private: std::wstring str2; public: blalabadsf(void); }; #include <string> using namespace std; wstring bla; ничего не срабатывает. может компилятор не настроен? Добавлено 13.04.10, 12:01 Сообщение отредактировано: Potroshitell — 13.04.10, 12:02 |
|
AZote |
|
|
инклудишь стринги после определения класса? О_о
#include <string> using namespace std; wstring bla; std::wstring str1; class blalabadsf { private: std::wstring str2; public: blalabadsf(void); }; |
|
Potroshitell |
|
|
как-то странно.. компилятор то компилит файл с кодом, то не компилит его же… тут какая-то путаница, я пока попробую разобраться.. Сообщение отредактировано: Potroshitell — 13.04.10, 12:49 |
Qraizer |
|
|
C или C++? |
|
Potroshitell |
|
|
с++ |
Qraizer |
|
|
А может вообще какой-нибудь CLI или C#? |
|
Potroshitell |
|
|
нене, с++)) |
|
aster_x |
|
|
Potroshitell AZote тебе все правильно распсиал. Сперва
#include <string> потом юзаешь стринги. |
0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
0 пользователей:
- Предыдущая тема
- Visual C++ / MFC / WTL
- Следующая тема
[ Script execution time: 0,0296 ] [ 16 queries used ] [ Generated: 29.01.23, 02:55 GMT ]


