1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
#ifndef __MULTIMAP_H__ #define __MULTIMAP_H__ #include <cstddef> template <class T, class keyT> struct mapstruct { keyT key; T info; mapstruct<T, keyT> *next; }; template <class T, class keyT> class multimap { public: multimap(); ~multimap(); void push(keyT&, T&); void pop(keyT&); class iterator { public: iterator(); mapstruct<T, keyT>* operator->(); iterator& operator++(int); private: mapstruct<T, keyT>* pointer; }; iterator begin(); private: mapstruct<T, keyT> *first; }; template <class T, class keyT> mapstruct<T, keyT>* multimap<T, keyT>::iterator::operator->() { return pointer; } template <class T, class keyT> multimap<T, keyT>::iterator& multimap<T, keyT>::iterator::operator++(int n) { pointer = pointer->next; return *this; } template <class T, class keyT> multimap<T, keyT>::multimap() { first = NULL; } template <class T, class keyT> multimap<T, keyT>::~multimap() { for (mapstruct<T, keyT> *cur = first; first != NULL; cur = first, first = first->next) delete cur; } template <class T, class keyT> void multimap<T, keyT>::push(keyT &key, T &info) { mapstruct<T, keyT> *newelement = new mapstruct<T, keyT>; newelement->key = key; newelement->info = info; newelement->next = first; first = newelement; } template <class T, class keyT> void multimap<T, keyT>::pop(keyT &key) { for (mapstruct<T, keyT> *prev = NULL, *cur = first; cur != NULL; prev = cur, cur = cur->next) if (cur->key == key) { mapstruct<T, keyT> *tmp = cur; if (prev != NULL) prev->next = cur = cur->next; else first = first->next; delete tmp; } } #endif |
Столкнулся с проблемой, но на существующих топиках об этой проблеме не нашел решения. Я в затруднении, все include’ы правильно расставлены вроде, да и средствами visual studio у меня получается перейти к объявлению функции, а ошибка все равно вылетает: «С2065. resizeCallback: необъявленный идентификатор». Вот код:
#pragma once
#include <iostream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#define internal static
#define local_persist static
#define global_variable static
namespace core {
namespace graphics {
class Window
{
private:
const char* name;
int width, height;
GLFWwindow* window;
public:
Window(const char* name, int width, int heignt);
~Window();
bool closed();
void MainLoop();
private:
bool init();
void clear();
void update();
void render();
friend void resizeCallback(GLFWwindow* window, int width, int height);
};
}}
Вот второй файл
#include "window.h"
namespace core {
namespace graphics {
Window::Window(const char* name, int width, int height)
{
this->name = name;
this->width = width;
this->height = height;
if (!init())
{
glfwTerminate();
}
}
Window::~Window()
{
glfwTerminate();
}
bool Window::init()
{
if (!glfwInit())
{
std::cout << "LooL. GLFW isn't ok" << std::endl;
glfwTerminate();
return false;
}
window = glfwCreateWindow(width, height, name, NULL, NULL);
glfwMakeContextCurrent(window);
glfwSetWindowSizeCallback(window, resizeCallback);
if (glewInit() != GLEW_OK)
{
std::cout << "glew isn't okay" << std::endl;
return false;
}
return true;
}
void Window::update()
{
glfwPollEvents();
glfwSwapBuffers(window);
}
void Window::clear()
{
glClear(GL_COLOR_BUFFER_BIT);
}
void Window::render()
{
glBegin(GL_QUADS);
glVertex2f(0.5f, 0.5f);
glVertex2f(0.5f, -0.5f);
glVertex2f(-0.5f, -0.5f);
glVertex2f(-0.5f, 0.5f);
glEnd();
}
void Window::MainLoop()
{
update();
clear();
render();
}
bool Window::closed()
{
return (glfwWindowShouldClose(window)) == 1;
}
void resizeCallback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
}}
description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid |
---|---|---|---|---|---|
Learn more about: Compiler Error C2065 |
Compiler Error C2065 |
06/29/2022 |
C2065 |
C2065 |
78093376-acb7-45f5-9323-5ed7e0aab1dc |
Compiler Error C2065
‘identifier‘ : undeclared identifier
The compiler can’t find the declaration for an identifier. There are many possible causes for this error. The most common causes of C2065 are that the identifier hasn’t been declared, the identifier is misspelled, the header where the identifier is declared isn’t included in the file, or the identifier is missing a scope qualifier, for example, cout
instead of std::cout
. For more information on declarations in C++, see Declarations and Definitions (C++).
Here are some common issues and solutions in greater detail.
The identifier is undeclared
If the identifier is a variable or a function name, you must declare it before it can be used. A function declaration must also include the types of its parameters before the function can be used. If the variable is declared using auto
, the compiler must be able to infer the type from its initializer.
If the identifier is a member of a class or struct, or declared in a namespace, it must be qualified by the class or struct name, or the namespace name, when used outside the struct, class, or namespace scope. Alternatively, the namespace must be brought into scope by a using
directive such as using namespace std;
, or the member name must be brought into scope by a using
declaration, such as using std::string;
. Otherwise, the unqualified name is considered to be an undeclared identifier in the current scope.
If the identifier is the tag for a user-defined type, for example, a class
or struct
, the type of the tag must be declared before it can be used. For example, the declaration struct SomeStruct { /*...*/ };
must exist before you can declare a variable SomeStruct myStruct;
in your code.
If the identifier is a type alias, the type must be declared by a using
declaration or typedef
before it can be used. For example, you must declare using my_flags = std::ios_base::fmtflags;
before you can use my_flags
as a type alias for std::ios_base::fmtflags
.
Example: misspelled identifier
This error commonly occurs when the identifier name is misspelled, or the identifier uses the wrong uppercase and lowercase letters. The name in the declaration must exactly match the name you use.
// C2065_spell.cpp // compile with: cl /EHsc C2065_spell.cpp #include <iostream> using namespace std; int main() { int someIdentifier = 42; cout << "Some Identifier: " << SomeIdentifier << endl; // C2065: 'SomeIdentifier': undeclared identifier // To fix, correct the spelling: // cout << "Some Identifier: " << someIdentifier << endl; }
Example: use an unscoped identifier
This error can occur if your identifier isn’t properly scoped. If you see C2065 when you use cout
, a scope issue is the cause. When C++ Standard Library functions and operators aren’t fully qualified by namespace, or you haven’t brought the std
namespace into the current scope by using a using
directive, the compiler can’t find them. To fix this issue, you must either fully qualify the identifier names, or specify the namespace with the using
directive.
This example fails to compile because cout
and endl
are defined in the std
namespace:
// C2065_scope.cpp // compile with: cl /EHsc C2065_scope.cpp #include <iostream> // using namespace std; // Uncomment this line to fix int main() { cout << "Hello" << endl; // C2065 'cout': undeclared identifier // C2065 'endl': undeclared identifier // Or try the following line instead std::cout << "Hello" << std::endl; }
Identifiers that are declared inside of class
, struct
, or enum class
types must also be qualified by the name of their enclosing scope when you use them outside of that scope.
Example: precompiled header isn’t first
This error can occur if you put any preprocessor directives, such as #include
, #define
, or #pragma
, before the #include
of a precompiled header file. If your source file uses a precompiled header file (that is, if it’s compiled by using the /Yu
compiler option) then all preprocessor directives before the precompiled header file are ignored.
This example fails to compile because cout
and endl
are defined in the <iostream>
header, which is ignored because it’s included before the precompiled header file. To build this example, create all three files, then compile pch.h
(some versions of Visual Studio use stdafx.cpp
), then compile C2065_pch.cpp
.
// pch.h (stdafx.h in Visual Studio 2017 and earlier) #include <stdio.h>
The pch.h
or stdafx.h
source file:
// pch.cpp (stdafx.cpp in Visual Studio 2017 and earlier) // Compile by using: cl /EHsc /W4 /c /Ycstdafx.h stdafx.cpp #include "pch.h"
Source file C2065_pch.cpp
:
// C2065_pch.cpp // compile with: cl /EHsc /W4 /Yustdafx.h C2065_pch.cpp #include <iostream> #include "stdafx.h" using namespace std; int main() { cout << "Hello" << endl; // C2065 'cout': undeclared identifier // C2065 'endl': undeclared identifier }
To fix this issue, add the #include of <iostream>
into the precompiled header file, or move it after the precompiled header file is included in your source file.
Example: missing header file
The error can occur if you haven’t included the header file that declares the identifier. Make sure the file that contains the declaration for the identifier is included in every source file that uses it.
// C2065_header.cpp // compile with: cl /EHsc C2065_header.cpp //#include <stdio.h> int main() { fpos_t file_position = 42; // C2065: 'fpos_t': undeclared identifier // To fix, uncomment the #include <stdio.h> line // to include the header where fpos_t is defined }
Another possible cause is if you use an initializer list without including the <initializer_list> header.
// C2065_initializer.cpp // compile with: cl /EHsc C2065_initializer.cpp // #include <initializer_list> int main() { for (auto strList : {"hello", "world"}) if (strList == "hello") // C2065: 'strList': undeclared identifier return 1; // To fix, uncomment the #include <initializer_list> line }
You may see this error in Windows Desktop app source files if you define VC_EXTRALEAN
, WIN32_LEAN_AND_MEAN
, or WIN32_EXTRA_LEAN
. These preprocessor macros exclude some header files from windows.h
and afxv_w32.h
to speed compiles. Look in windows.h
and afxv_w32.h
for an up-to-date description of what’s excluded.
Example: missing closing quote
This error can occur if you’re missing a closing quote after a string constant. It’s an easy way to confuse the compiler. The missing closing quote may be several lines before the reported error location.
// C2065_quote.cpp // compile with: cl /EHsc C2065_quote.cpp #include <iostream> int main() { // Fix this issue by adding the closing quote to "Aaaa" char * first = "Aaaa, * last = "Zeee"; std::cout << "Name: " << first << " " << last << std::endl; // C2065: 'last': undeclared identifier }
Example: use iterator outside for loop scope
This error can occur if you declare an iterator variable in a for
loop, and then you try to use that iterator variable outside the scope of the for
loop. The compiler enables the /Zc:forScope
compiler option by default. For more information, see Debug iterator support.
// C2065_iter.cpp // compile with: cl /EHsc C2065_iter.cpp #include <iostream> #include <string> int main() { // char last = '!'; std::string letters{ "ABCDEFGHIJKLMNOPQRSTUVWXYZ" }; for (const char& c : letters) { if ('Q' == c) { std::cout << "Found Q!" << std::endl; } // last = c; } std::cout << "Last letter was " << c << std::endl; // C2065 // Fix by using a variable declared in an outer scope. // Uncomment the lines that declare and use 'last' for an example. // std::cout << "Last letter was " << last << std::endl; // C2065 }
Example: preprocessor removed declaration
This error can occur if you refer to a function or variable that is in conditionally compiled code that isn’t compiled for your current configuration. The error can also occur if you call a function in a header file that currently isn’t supported in your build environment. If certain variables or functions are only available when a particular preprocessor macro is defined, make sure the code that calls those functions can only be compiled when the same preprocessor macro is defined. This issue is easy to spot in the IDE: The declaration for the function is greyed out if the required preprocessor macros aren’t defined for the current build configuration.
Here’s an example of code that works when you build in Debug, but not Release:
// C2065_defined.cpp // Compile with: cl /EHsc /W4 /MT C2065_defined.cpp #include <iostream> #include <crtdbg.h> #ifdef _DEBUG _CrtMemState oldstate; #endif int main() { _CrtMemDumpStatistics(&oldstate); std::cout << "Total count " << oldstate.lTotalCount; // C2065 // Fix by guarding references the same way as the declaration: // #ifdef _DEBUG // std::cout << "Total count " << oldstate.lTotalCount; // #endif }
Example: C++/CLI type deduction failure
This error can occur when calling a generic function, if the intended type argument can’t be deduced from the parameters used. For more information, see Generic Functions (C++/CLI).
// C2065_b.cpp // compile with: cl /clr C2065_b.cpp generic <typename ItemType> void G(int i) {} int main() { // global generic function call G<T>(10); // C2065 G<int>(10); // OK - fix with a specific type argument }
Example: C++/CLI attribute parameters
This error can also be generated as a result of compiler conformance work that was done for Visual Studio 2005: parameter checking for Visual C++ attributes.
// C2065_attributes.cpp // compile with: cl /c /clr C2065_attributes.cpp [module(DLL, name=MyLibrary)]; // C2065 // try the following line instead // [module(dll, name="MyLibrary")]; [export] struct MyStruct { int i; };
5 ответов
Он не определен в вашей программе. Обычно это определяется в стандартном файле заголовка (в частности, cstddef или stddef.h). Поскольку вы ограничены iostream, если ваш не получает NULL неявно из этого заголовка, вы также можете использовать 0 или, в С++ 11, nullptr
, который является ключевым словом и не требует заголовка.
metal
21 март 2013, в 14:46
Поделиться
Вы должны включить <stddef.h>
или <cstddef>
.
Однако вы можете использовать 0
или nullptr
тоже.
deepmax
21 март 2013, в 15:59
Поделиться
используйте следующее:
#include <stddef.h>
ryrich
21 март 2013, в 15:41
Поделиться
Никаких библиотек не требуется!
в верхней части файла заголовка,
сделайте следующее:
#ifndef NULL
#define NULL (0)
#endif
Aniket Inge
21 март 2013, в 14:45
Поделиться
NULL
на самом деле не является частью основного языка C или С++; он определяется как 0 в stddef.h
Поскольку вы используете С++, предпочитайте nullptr
, который является ключевым словом, и набирается. (Предположим, что это доступно. Это часть С++ 11, поэтому технически не все компиляторы будут ее поддерживать, практически вам будет сложно найти компилятор, который этого не делает)
Chowlett
21 март 2013, в 14:34
Поделиться
Ещё вопросы
- 0DropdownList для значения по умолчанию с ng-моделью
- 1Проблема при запуске нескольких пакетных файлов из одного пакетного файла
- 1Java: Что происходит с предполагаемыми инициализированными членами при передаче значения их объекту во время создания?
- 1оператор import отображает ошибку «Нет такого модуля»
- 1DropDownListFor для статического списка состояний
- 0Я не могу определить конечный символ n в моем операторе if
- 1Краткий способ объявить матовую матрицу
- 0Кнопка «Назад» и слайд-шоу
- 1Почему таймер matplotlib ускоряется при нажатии кнопки PyQt?
- 0ошибка утечки окна не решена после вставки данных в MySQL
- 0Как смоделировать выпадающий список с вводом?
- 1Утечка памяти Android, без статических переменных
- 1Нет пути конвертации для проблемы dtype (‘<U1’)
- 0ожидается путь для присоединения JPA Hibernate MySQL
- 0Неспособность открыть файл
- 0Неинтенсивное двустороннее связывание данных в угловом моде с начальной загрузкой
- 1Установка скрипта Python в ImageJ
- 1Как получить количество всех вариантов (скажем, из опроса) в виде столбцов
- 0Как скрыть атрибут метки опции выбора?
- 1Форматирование всплывающей подсказки круговой диаграммы
- 0Чтение из сокета со смещением с флагом MSG_PEEK?
- 0Рассчитать сумму подписки новых пользователей MySQL
- 0Пул MySQL в nodejs
- 0Неразрешенное включение
- 1Поиск победителя в Tic-Tac-Toe (Java с использованием 2-D массивов)
- 1Входные строки должны быть кратны 16 Python Pycrypto
- 0Добавить drupal в существующий проект Angular
- 0Внешняя ссылка не работает в FF, Chrome, но работает в IE 9
- 0Экспорт Swing JTable в Excel с тегами HTML
- 1Как оживить взгляды?
- 1NodeJS затем / catch в функции, кажется, ловит код вне функции
- 1получить местоположение файла в Android?
- 1Как использовать python, чтобы проверить, установлен ли maven
- 0unlink и DELETE FROM не будут работать
- 1Динамическое выполнение веб-служб на основе SOAP без создания прокси
- 1Форсировать два знака после запятой в C #
- 0Перегрузить оператор вывода << для работы с итератором списка STL
- 0ошибка c2953: шаблон класса уже определен
- 0PHP несколько способов сброса переменной
- 0Класс с 2 условиями
- 0JQPlot, JSON и ошибка «Данные не указаны»
- 0Повторно примените стиль div, используя jQuery
- 0Класс векторов с определенной длиной
- 0чтение удваивается из файла .csv в C ++
- 0Выберите отдельные значения в одну результирующую запись в виде списка через запятую
- 0Как поместить частичный вид MVC в лайтбокс?
- 1В карточной игре Java, как бы я ненадолго остановился после раздачи каждой карты в руку?
- 1Правильный способ записи данных JSON, возвращаемых из запроса SPARQL в Python
- 0Как $ смотреть поле на заводе angularJS
- 0перебрать 10 дней и сохранить каждую дату в массиве
Я пытаюсь скомпилировать исходники с Visual Studio 2008 Express, но я получаю эту ошибку:
Error C2065: 'nullptr' undeclared identifier.
Мой код:
if (Data == nullptr)
{
show("Data is null");
return 0;
}
Я прочитал в Google, что мне нужно перейти на Visual Studio 2010, но я не хочу этого делать из-за intelisense 2008 года. Это можно починить или заменить?
4
Решение
Вы получаете ошибку, потому что компилятор не распознает nullptr
ключевое слово. Это потому что nullptr
была представлена в более поздней версии Visual Studio, чем та, которую вы используете.
Есть два способа заставить это работать в старой версии. Одна идея пришла из книги Скотта Мейерса c ++, где он предлагает создать заголовок с классом, который эмулирует nullptr
как это:
const // It is a const object...
class nullptr_t
{
public:
template<class T>
inline operator T*() const // convertible to any type of null non-member pointer...
{ return 0; }
template<class C, class T>
inline operator T C::*() const // or any type of null member pointer...
{ return 0; }
private:
void operator&() const; // Can't take address of nullptr
} nullptr = {};
Таким образом, вам просто нужно условно включить файл в зависимости от версии msvc
#if _MSC_VER < 1600 //MSVC version <8
#include "nullptr_emulation.h"#endif
Это имеет преимущество в использовании того же ключевого слова и делает обновление до нового компилятора довольно простым (и, пожалуйста, сделайте обновление, если можете). Если вы сейчас компилируете с более новым компилятором, то ваш пользовательский код вообще не используется, и вы используете только язык c ++, я чувствую, что это важно в будущем.
Если вы не хотите использовать этот подход, вы можете использовать что-то, что эмулирует старый подход в стиле C (#define NULL ((void *)0)
) где вы делаете макрос для NULL
как это:
#define NULL 0
if(data == NULL){
}
Обратите внимание, что это не совсем то же самое, что NULL
как найдено в C, для дальнейшего обсуждения см. этот вопрос: Почему указатели NULL по-разному определяются в C и C ++?
Недостатками этого является то, что вы должны изменить исходный код, и он не является безопасным nullptr
, Так что используйте это с осторожностью, это может привести к некоторым тонким ошибкам, если вы не будете осторожны, и именно эти тонкие ошибки мотивировали развитие nullptr
на первом месте.
7
Другие решения
nullptr
является частью C ++ 11, в C ++ 03 вы просто используете 0
:
if (!Data)
5
Содержание
- Compiler Error C2065
- The identifier is undeclared
- Example: misspelled identifier
- Example: use an unscoped identifier
- Example: precompiled header isn’t first
- Example: missing header file
- Example: missing closing quote
- Example: use iterator outside for loop scope
- Example: preprocessor removed declaration
- Example: C++/CLI type deduction failure
- Example: C++/CLI attribute parameters
- Ошибка C2065: ‘cout’: необъявленный идентификатор
- ОТВЕТЫ
- Ответ 1
- Ответ 2
- Ответ 3
- Ответ 4
- Ответ 5
- Ответ 6
- Ответ 7
- Ответ 8
- Ответ 9
- Ответ 10
- Ответ 11
- Ответ 12
- Ответ 13
- Ответ 14
- Ответ 15
- Ответ 16
- Ответ 17
- Ответ 18
- Ответ 19
- Ответ 20
- Ответ 21
- Ответ 22
- Ответ 23
- Ответ 24
- Что такое ошибка «необъявленный идентификатор» и как ее исправить?
- 8 ответов
- Отсутствует заголовок
- Неверная переменная
- Неверная область действия
- Использовать перед объявлением
Compiler Error C2065
The compiler can’t find the declaration for an identifier. There are many possible causes for this error. The most common causes of C2065 are that the identifier hasn’t been declared, the identifier is misspelled, the header where the identifier is declared isn’t included in the file, or the identifier is missing a scope qualifier, for example, cout instead of std::cout . For more information on declarations in C++, see Declarations and Definitions (C++).
Here are some common issues and solutions in greater detail.
The identifier is undeclared
If the identifier is a variable or a function name, you must declare it before it can be used. A function declaration must also include the types of its parameters before the function can be used. If the variable is declared using auto , the compiler must be able to infer the type from its initializer.
If the identifier is a member of a class or struct, or declared in a namespace, it must be qualified by the class or struct name, or the namespace name, when used outside the struct, class, or namespace scope. Alternatively, the namespace must be brought into scope by a using directive such as using namespace std; , or the member name must be brought into scope by a using declaration, such as using std::string; . Otherwise, the unqualified name is considered to be an undeclared identifier in the current scope.
If the identifier is the tag for a user-defined type, for example, a class or struct , the type of the tag must be declared before it can be used. For example, the declaration struct SomeStruct < /*. */ >; must exist before you can declare a variable SomeStruct myStruct; in your code.
If the identifier is a type alias, the type must be declared by a using declaration or typedef before it can be used. For example, you must declare using my_flags = std::ios_base::fmtflags; before you can use my_flags as a type alias for std::ios_base::fmtflags .
Example: misspelled identifier
This error commonly occurs when the identifier name is misspelled, or the identifier uses the wrong uppercase and lowercase letters. The name in the declaration must exactly match the name you use.
Example: use an unscoped identifier
This error can occur if your identifier isn’t properly scoped. If you see C2065 when you use cout , a scope issue is the cause. When C++ Standard Library functions and operators aren’t fully qualified by namespace, or you haven’t brought the std namespace into the current scope by using a using directive, the compiler can’t find them. To fix this issue, you must either fully qualify the identifier names, or specify the namespace with the using directive.
This example fails to compile because cout and endl are defined in the std namespace:
Identifiers that are declared inside of class , struct , or enum class types must also be qualified by the name of their enclosing scope when you use them outside of that scope.
This error can occur if you put any preprocessor directives, such as #include , #define , or #pragma , before the #include of a precompiled header file. If your source file uses a precompiled header file (that is, if it’s compiled by using the /Yu compiler option) then all preprocessor directives before the precompiled header file are ignored.
This example fails to compile because cout and endl are defined in the header, which is ignored because it’s included before the precompiled header file. To build this example, create all three files, then compile pch.h (some versions of Visual Studio use stdafx.cpp ), then compile C2065_pch.cpp .
The pch.h or stdafx.h source file:
Source file C2065_pch.cpp :
To fix this issue, add the #include of into the precompiled header file, or move it after the precompiled header file is included in your source file.
The error can occur if you haven’t included the header file that declares the identifier. Make sure the file that contains the declaration for the identifier is included in every source file that uses it.
Another possible cause is if you use an initializer list without including the header.
You may see this error in Windows Desktop app source files if you define VC_EXTRALEAN , WIN32_LEAN_AND_MEAN , or WIN32_EXTRA_LEAN . These preprocessor macros exclude some header files from windows.h and afxv_w32.h to speed compiles. Look in windows.h and afxv_w32.h for an up-to-date description of what’s excluded.
Example: missing closing quote
This error can occur if you’re missing a closing quote after a string constant. It’s an easy way to confuse the compiler. The missing closing quote may be several lines before the reported error location.
Example: use iterator outside for loop scope
This error can occur if you declare an iterator variable in a for loop, and then you try to use that iterator variable outside the scope of the for loop. The compiler enables the /Zc:forScope compiler option by default. For more information, see Debug iterator support.
Example: preprocessor removed declaration
This error can occur if you refer to a function or variable that is in conditionally compiled code that isn’t compiled for your current configuration. The error can also occur if you call a function in a header file that currently isn’t supported in your build environment. If certain variables or functions are only available when a particular preprocessor macro is defined, make sure the code that calls those functions can only be compiled when the same preprocessor macro is defined. This issue is easy to spot in the IDE: The declaration for the function is greyed out if the required preprocessor macros aren’t defined for the current build configuration.
Here’s an example of code that works when you build in Debug, but not Release:
Example: C++/CLI type deduction failure
This error can occur when calling a generic function, if the intended type argument can’t be deduced from the parameters used. For more information, see Generic Functions (C++/CLI).
Example: C++/CLI attribute parameters
This error can also be generated as a result of compiler conformance work that was done for Visual Studio 2005: parameter checking for Visual C++ attributes.
Источник
Ошибка C2065: ‘cout’: необъявленный идентификатор
Я работаю над частью «драйвера» моего назначения программирования, и я продолжаю получать эту абсурдную ошибку:
ошибка C2065: ‘cout’: необъявленный идентификатор
Я даже пытался использовать std:: cout, но я получаю еще одну ошибку, которая говорит: IntelliSense: пространство имен «std» не имеет члена «cout» , когда у меня есть объявленный с использованием пространства имен std, включая iostream +, я даже пытался использовать ostream
Я знаю, что это стандартный вопрос о нобе, но это меня насторожило, и я новичок (это означает: я запрограммировал раньше. )
Я использую Visual Studio 2010 и запускаю Windows 7. Все файлы .h имеют «использование пространства имен std» и включают iostream и ostream.
ОТВЕТЫ
Ответ 1
В Visual Studio вы должны #include «stdafx.h» и быть первым включением файла cpp. Например:
Это не будет работать.
Ответ 2
напишите этот код, он отлично работает.
Ответ 3
У меня была такая же проблема на Visual Studio С++ 2010. Это легко исправить. Над функцией main() просто замените стандартные строки с этим ниже, но с символом фунта перед включенными.
Ответ 4
include «stdafx.h» в порядке
Но вы не можете использовать cout , если вы не включили using namespace std
Если вы не включили пространство имен std, вам нужно написать std::cout вместо простого cout
Ответ 5
Я видел, что если вы используете
тогда вы получите эту проблему.
Если вы используете
(уведомление — без .h)
то вы не получите проблему, о которой вы упомянули.
Ответ 6
Если вы начали проект, требующий строки #include «stdafx.h» , поставьте его первым.
Ответ 7
Нижеприведенный код компилируется и запускается правильно для меня, используя gcc. Попробуйте скопировать/вставить это и посмотреть, работает ли он.
Ответ 8
Если единственным файлом, который вы включаете, является iostream, и он все еще говорит undefined, то, возможно, iostream не содержит того, что он должен был. Возможно ли, что у вас есть пустой файл, совпадающий по имени «iostream» в вашем проекте?
Ответ 9
Я видел похожие вещи, когда я использовал расширение .c файла с кодом С++. Кроме этого, я должен согласиться со всеми о багги установке. Это работает, если вы попытаетесь скомпилировать проект с более ранней версией VS? Попробуйте VС++ Express 2008. Его бесплатно на msdn.
Ответ 10
Такое глупое решение в моем случае:
Выше было указано в качестве примера a, когда я изменил его, чтобы он был похож на пример b ниже.
Мой код составлен как шарм. Попробуйте, гарантированно сработает.
Ответ 11
прежде чем вы начнете эту программу, избавитесь от всего кода и сделайте простой мир привет внутри основного. Включать только iostream и использовать пространство имен std;. Постепенно добавьте его, чтобы найти свою проблему.
Ответ 12
У меня есть VS2010, Beta 1 и Beta 2 (один на моей рабочей машине и один на дому), и я использовал std множество без проблем. Попробуйте ввести:
И посмотрите, дает ли Intellisense что-нибудь. Если это дает вам обычный материал ( abort , abs , acos и т.д.), За исключением cout , ну тогда это довольно головоломка. Определенно посмотрите на ваши заголовки С++ в этом случае.
Помимо этого, я бы просто добавил, чтобы убедиться, что вы используете обычный пустой проект (не CLR, где Intellisense поврежден), и что вы на самом деле пытались построить проект хотя бы один раз. Как я уже упоминал в комментарии, VS2010 анализирует файлы после добавления include ; возможно, что что-то застряло в парсере, и он не сразу «нашел» cout . (В этом случае попробуйте перезапустить VS, возможно?)
Ответ 13
У меня была такая же проблема при запуске проекта ms С++ 2010 с нуля — я удалил все файлы заголовков, сгенерированные с помощью ms, но использовал:
Мне пришлось включить stdafx.h , поскольку это вызвало ошибку, в которой он не был.
Ответ 14
из вашего .cpp файла, создайте файл заголовка и поместите его в файл .h. Затем добавьте
в верхней части вашего .cpp-кода. Затем запустите его снова.
Ответ 15
Вы уверены, что он компилируется как С++? Проверьте имя файла (он должен заканчиваться на .cpp ). Проверьте настройки проекта.
Нет ничего плохого в вашей программе, а cout находится в namespace std . Ваша установка VS 2010 Beta 2 является дефектной, и я не думаю, что это просто ваша установка.
Я не думаю, что VS 2010 готов к С++. Стандартная программа «Hello, World» не работала на бета-версии 1. Я просто попытался создать тестовое консольное приложение Win32, а сгенерированный файл test.cpp не имел функции main() .
У меня действительно очень плохое чувство о VS 2010.
Ответ 16
Попробуй, это сработает. Я проверил его в Windows XP, Visual Studio 2010 Express.
Ответ 17
Когда вы создали свой проект, вы не установили правильно использовать предварительно скомпилированные заголовки. Измените его в свойствах → C/С++ → предварительно скомпилированные заголовки.
Ответ 18
В Visual Studio используйте весь ваш фильтр заголовка ниже «stdafx.h».
Ответ 19
Включите библиотеку std, вставив следующую строку вверху вашего кода:
Ответ 20
обычно сохраняется в папке C:Program FilesMicrosoft Visual Studio 8VCinclude. Сначала проверьте, все ли он там. Затем выберите «Инструменты + варианты», «Проекты и решения», «Каталоги VС++», выберите «Включить файлы» в поле «Показать каталоги для» и дважды проверьте, что включение (VCInstallDir) включено в список.
Ответ 21
Я столкнулся с этой ошибкой после того, как установил vs 2010 и просто пытался получить почти идентичную программу для работы.
Я уже делал кодировку ваниль C в коробках в стиле unix, решил, что немного поиграю с этим.
Первая программа, которую я пробовал, была:
Большая вещь, чтобы заметить здесь. если вы все сделали C-кодирование,
Выглядит странно. это должно быть:
В моем случае я просто изменил программу на:
И он отлично работал.
Примечание. Используйте CTRL + F5, чтобы окно консоли закрывалось, чтобы вы могли видеть результаты.
Ответ 22
Просто используйте printf !
Включите stdio.h в заголовочный файл stdafx.h для printf .
Ответ 23
Я пришел сюда, потому что у меня была такая же проблема, но когда я сделал #include «stdafx.h» , он сказал, что не нашел этот файл.
Что для меня было трюком: #include .
Я использую Microsoft Visual Studio 2008.
Это то, что вы можете использовать тогда, в том числе. ‘count’: Ссылка
Ответ 24
Это был компилятор — теперь я использую Eclipse Galileo, и программа работает как чудо
Источник
Что такое ошибка «необъявленный идентификатор» и как ее исправить?
Что такое необъявленные ошибки идентификатора? Каковы общие причины и как их исправить?
Примеры текстов ошибок:
- Для компилятора Visual Studio: error C2065: ‘printf’ : undeclared identifier
- Для компилятора GCC: `printf’ undeclared (first use in this function)
8 ответов
Они чаще всего приходят из забывания включить заголовочный файл, содержащий объявление функции, например, эта программа даст ошибку «необъявленного идентификатора»:
Отсутствует заголовок
Чтобы исправить это, мы должны включить заголовок:
Если вы написали заголовок и включили его правильно, заголовок может содержать неправильный include guard.
Неверная переменная
Другой распространенный источник ошибки начинающего возникает, когда вы ошибочно написали переменную:
Неверная область действия
Например, этот код даст ошибку, потому что вам нужно использовать std::string :
Использовать перед объявлением
g не был объявлен до его первого использования. Чтобы исправить это, переместите определение g до f :
Или добавьте объявление g до f :
Не стесняйтесь редактировать этот ответ.
Рассмотрим аналогичную ситуацию в разговоре. Представьте, что ваш друг говорит вам: «Боб подходит к обеду», и вы не знаете, кто такой Боб. Вы будете в замешательстве, верно? Ваш друг должен был сказать: «У меня есть коллега по работе по имени Боб. Боб подходит к обеду». Теперь Боб был объявлен, и вы знаете, о чём говорит ваш друг.
Компилятор испускает ошибку «необъявленного идентификатора», когда вы пытаетесь использовать какой-то идентификатор (что будет именем функции, переменной, класса и т.д.), и компилятор не видел для него объявления. То есть, компилятор понятия не имеет, о чем вы говорите, потому что раньше этого не видел.
Если вы получаете такую ошибку в C или С++, это означает, что вы не сказали компилятору о том, что вы пытаетесь использовать. Объявления часто встречаются в заголовочных файлах, поэтому, вероятно, это означает, что вы не включили соответствующий заголовок. Конечно, возможно, вы просто не помнили, чтобы вообще объявлять сущность.
Некоторые компиляторы дают более конкретные ошибки в зависимости от контекста. Например, попытка скомпилировать X x; , где тип X не был объявлен с clang, скажет вам «неизвестное имя типа X «. Это гораздо более полезно, потому что вы знаете, что пытаетесь интерпретировать X как тип. Однако, если у вас есть int x = y; , где y еще не объявлен, он скажет вам «использование незаявленного идентификатора y «, потому что существует некоторая неопределенность в отношении того, что может представлять собой y .
В C и С++ все имена должны быть объявлены до их использования. Если вы попытаетесь использовать имя переменной или функцию, которая не была объявлена, вы получите ошибку «необъявленный идентификатор».
Однако функции являются частным случаем в C (и только в C), поскольку вам не нужно сначала объявлять их. Компилятор C будет считать, что функция существует с количеством и типом аргументов, как в вызове. Если фактическое определение функции не соответствует, вы получите еще одну ошибку. Этот специальный случай для функций не существует в С++.
Вы исправляете эти ошибки, убедившись, что функции и переменные объявлены до их использования. В случае printf вам нужно включить заголовочный файл (или в С++).
Для стандартных функций я рекомендую вам проверить, например. этот справочный сайт и выполните поиск функций, которые вы хотите использовать. Документация для каждой функции сообщает вам, какой файл заголовка вам нужен.
Эти сообщения об ошибках
означает, что вы используете имя printf , но компилятор не видит, где было объявлено имя и, соответственно, не знает, что это значит.
Любое имя, используемое в программе, должно быть объявлено до его использования. Компилятор должен знать, что означает это имя.
В этом конкретном случае компилятор не видит объявления с именем printf . Как мы знаем (но не компилятор), это имя стандартной функции C, объявленной в заголовке в C или в заголовке в С++, и помещается в стандартную ( std:: ) и глобальную ( :: ) ( не обязательно) пространства имен.
Поэтому перед использованием этой функции мы должны предоставить объявление своего имени компилятору, включив соответствующие заголовки.
Например С
С++:
Иногда причиной такой ошибки является простая опечатка. Например, допустим, что вы определили функцию PrintHello
но в основном вы сделали опечатку, а вместо PrintHello вы набрали PrintHello строчной буквой «p».
В этом случае компилятор выдает такую ошибку, потому что не видит объявления имени PrintHello . PrintHello и PrintHello — это два разных имени, одно из которых было объявлено, а другое не было объявлено, а использовано в теле основного
Источник
Здравствуйте. Я новичок в C++. На работе ковыряюсь в чужом проекте. В файле есть два метода. В одном из них используется класс. Я хочу использовать этот класс в другом методе, на что компилятор выдает error C2065: undeclared identifier. Вот схематичное описание ситуации:
temlate<class Base>
class CLASS
{
void visit()
{
// bla bla bla
Device d; // 'Device' : undeclared identifier
//bla bla bla
}
void Draw()
{
// bla bla bla
Device d; // It's OK
//bla bla bla
}
};
Не могу понять почему это так. Пробовал менять методы местами, но ошибка остается, причем именно на ту же самую строку (в методе visit). Подскажите пожалуйста как это исправить. Заранее спасибо!
UPD:
Если закомментировать использование Device в методе visit, то все отлично работает (проект рабочий, я его просто допиливаю):
class CLASS
{
void visit()
{
// bla bla bla
// Device d; // now it's OK
//bla bla bla
}
void Draw()
{
// bla bla bla
Device d; // It's OK
//bla bla bla
}
};