Error c2065 undeclared identifier error c2065 undeclared identifier

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 […]

Содержание

  1. Compiler Error C2065
  2. The identifier is undeclared
  3. Example: misspelled identifier
  4. Example: use an unscoped identifier
  5. Example: precompiled header isn’t first
  6. Example: missing header file
  7. Example: missing closing quote
  8. Example: use iterator outside for loop scope
  9. Example: preprocessor removed declaration
  10. Example: C++/CLI type deduction failure
  11. Example: C++/CLI attribute parameters
  12. Ошибка компилятора C2065
  13. Идентификатор является необъявленным
  14. Пример: идентификатор с ошибками
  15. Пример. Использование несеченного идентификатора
  16. Пример: предварительно скомпилированные заголовки не первый
  17. Пример: отсутствующий файл заголовка
  18. Пример: отсутствует закрывающая цитата
  19. Пример. Использование итератора вне для области цикла
  20. Пример: объявление препроцессора удалено
  21. Пример: Сбой вычета типа C++/CLI
  22. Пример. Параметры атрибута C++/CLI
  23. Name already in use
  24. cpp-docs / docs / error-messages / compiler-errors-1 / compiler-error-c2065.md

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

Компилятор не может найти объявление для идентификатора. Эта ошибка имеет несколько возможных причин. Наиболее распространенные причины C2065 : идентификатор не был объявлен, идентификатор написан с ошибками, заголовок, в котором объявлен идентификатор, не включен в файл, или в идентификаторе отсутствует квалификатор области, например, cout вместо std::cout . Дополнительные сведения о объявлениях в C++ см. в разделе Объявления и определения (C++).

Ниже приведены некоторые распространенные проблемы и их решения.

Идентификатор является необъявленным

Если идентификатор является переменной или именем функции, его необходимо объявить, прежде чем его можно будет использовать. Объявление функции должно также включать типы ее параметров, прежде чем можно будет использовать функцию. Если переменная объявлена с помощью auto , компилятор должен иметь возможность определить тип из инициализатора.

Если идентификатор является членом класса или структуры или объявлен в пространстве имен, он должен быть квалифицирован по имени класса или структуры или имени пространства имен при использовании за пределами области структуры, класса или пространства имен. Кроме того, пространство имен должно быть передано в область с помощью using директивы, например using namespace std; , или имя члена должно быть передано в область с помощью using объявления, например using std::string; . В противном случае непроверенное имя считается необъявленным идентификатором в текущей области.

Если идентификатор является тегом для определяемого пользователем class типа, например или struct , тип тега необходимо объявить, прежде чем его можно будет использовать. Например, объявление struct SomeStruct < /*. */ >; должно существовать, прежде чем можно будет объявить переменную SomeStruct myStruct; в коде.

Если идентификатор является псевдонимом типа, тип должен быть объявлен объявлением using или typedef перед его использованием. Например, необходимо объявить using my_flags = std::ios_base::fmtflags; перед использованием my_flags в качестве псевдонима типа для std::ios_base::fmtflags .

Пример: идентификатор с ошибками

Эта ошибка обычно возникает, если имя идентификатора написано с ошибкой или идентификатор использует неправильные прописные и строчные буквы. Имя в объявлении должно точно соответствовать используемому имени.

Пример. Использование несеченного идентификатора

Эта ошибка может возникнуть, если область действия идентификатора не задана должным образом. Если при использовании cout отображается C2065 , причина заключается в проблеме области. Если функции и операторы стандартной библиотеки C++ не полностью определяются пространством имен или вы не включили std пространство имен в текущую using область с помощью директивы , компилятор не сможет найти их. Чтобы устранить эту проблему, необходимо либо полностью указать имена идентификаторов, либо указать пространство имен с помощью директивы using .

В этом примере не удается выполнить компиляцию, так как cout и endl определены в std пространстве имен:

Идентификаторы, объявленные в типах class , struct или enum class , также должны быть квалифицированы по имени включающей области при их использовании за пределами этой области.

Пример: предварительно скомпилированные заголовки не первый

Эта ошибка может возникнуть, если перед файлом предварительно скомпилированного файла заголовка были помещены директивы препроцессора, например #include , #define или #pragma . #include Если исходный файл использует предварительно скомпилированный файл заголовка (то есть, если он компилируется с помощью /Yu параметра компилятора), то все директивы препроцессора, предшествующие предварительно скомпилированному файлу заголовка, игнорируются.

В этом примере не удается выполнить компиляцию, так как cout и endl определены в заголовке , который игнорируется, так как он включен перед предварительно скомпилированным файлом заголовка. Чтобы выполнить сборку этого примера, создайте все три файла, затем скомпилируйте pch.h (в некоторых версиях Visual Studio используется stdafx.cpp ), а затем скомпилируйте C2065_pch.cpp .

Исходный pch.h файл или stdafx.h :

Исходный файл C2065_pch.cpp :

Чтобы устранить эту проблему, добавьте #include в файл предкомпилированного заголовка или переместите его после включения предварительно скомпилированного файла заголовка в исходный файл.

Пример: отсутствующий файл заголовка

Ошибка может возникнуть, если вы не включили файл заголовка, в который объявляется идентификатор. Убедитесь, что файл, содержащий объявление идентификатора, включен в каждый исходный файл, в котором он используется.

Другой возможной причиной является использование списка инициализаторов без включения заголовка .

Эта ошибка может возникнуть в исходных файлах классического приложения Для Windows, если вы определяете VC_EXTRALEAN , WIN32_LEAN_AND_MEAN или WIN32_EXTRA_LEAN . Эти макросы препроцессора исключают некоторые файлы заголовков из windows.h и afxv_w32.h для ускорения компиляции. Найдите в windows.h и afxv_w32.h актуальное описание того, что исключается.

Пример: отсутствует закрывающая цитата

Эта ошибка может возникнуть, если отсутствует закрывающая кавычка после строковой константы. Это простой способ запутать компилятор. Отсутствующие закрывающие кавычки могут находиться в нескольких строках перед сообщаемой ошибкой.

Пример. Использование итератора вне для области цикла

Эта ошибка может возникнуть, если объявить переменную итератора в for цикле, а затем попытаться использовать эту переменную итератора вне области for цикла. Компилятор включает параметр компилятора /Zc:forScope по умолчанию. Дополнительные сведения см. в разделе Поддержка итератора отладки.

Пример: объявление препроцессора удалено

Эта ошибка может возникнуть, если вы ссылаетесь на функцию или переменную, которая находится в условно скомпилированном коде, который не компилируется для текущей конфигурации. Эта ошибка также может возникнуть при вызове функции в файле заголовка, которая в настоящее время не поддерживается в среде сборки. Если определенные переменные или функции доступны только при определении определенного макроса препроцессора, убедитесь, что код, вызывающий эти функции, может быть скомпилирован только при определении того же макроса препроцессора. Эту проблему легко обнаружить в интегрированной среде разработки: объявление для функции неактивно, если необходимые макросы препроцессора не определены для текущей конфигурации сборки.

Ниже приведен пример кода, который работает при сборке в отладке, но не в выпуске:

Пример: Сбой вычета типа C++/CLI

Эта ошибка может возникнуть при вызове универсальной функции, если предполагаемый аргумент типа не может быть выведен из используемых параметров. Дополнительные сведения см. в разделе Универсальные функции (C++/CLI).

Пример. Параметры атрибута C++/CLI

Эта ошибка также может быть создана в результате работы компилятора по соответствунию, выполненной для Visual Studio 2005: проверка параметров для атрибутов Visual C++.

Источник

Name already in use

cpp-docs / docs / error-messages / compiler-errors-1 / compiler-error-c2065.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink

Copy raw contents

Copy raw contents

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.

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 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.

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.

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.

Источник

  • Remove From My Forums
  • Question

  • void AFH_RGB24_C(uc* p, int height, const int pitch, const int width, const int amount) {
      const int center_weight = amount*2;
      const int outer_weight = 32768-amount;
      for (int y = height; y>0; —y)
        {

          uc bb = p[0];
          uc gg = p[1];
          uc rr = p[2];
          for (int x = 0; x < width-1; ++x)
          {
            uc b = ScaledPixelClip(p[x*3+0] * center_weight + (bb + p[x*3+3]) * outer_weight);
            bb = p[x*3+0]; p[x*3+0] = b;
            uc g = ScaledPixelClip(p[x*3+1] * center_weight + (gg + p[x*3+4]) * outer_weight);
            gg = p[x*3+1]; p[x*3+1] = g;
            uc r = ScaledPixelClip(p[x*3+2] * center_weight + (rr + p[x*3+5]) * outer_weight);
            rr = p[x*3+2]; p[x*3+2] = r;
          }
          p[x*3+0] = ScaledPixelClip(p[x*3+0] * center_weight + (bb + p[x*3+0]) * outer_weight);
          p[x*3+1] = ScaledPixelClip(p[x*3+1] * center_weight + (gg + p[x*3+1]) * outer_weight);
          p[x*3+2] = ScaledPixelClip(p[x*3+2] * center_weight + (rr + p[x*3+2]) * outer_weight);

          p += pitch;
        }
    }

    ________

    Error message: 
    1>.focus.cpp(731) : error C2065: ‘x’ : undeclared identifier
    1>.focus.cpp(731) : error C2065: ‘x’ : undeclared identifier
    1>.focus.cpp(731) : error C2065: ‘x’ : undeclared identifier
    1>.focus.cpp(732) : error C2065: ‘x’ : undeclared identifier
    1>.focus.cpp(732) : error C2065: ‘x’ : undeclared identifier
    1>.focus.cpp(732) : error C2065: ‘x’ : undeclared identifier
    1>.focus.cpp(733) : error C2065: ‘x’ : undeclared identifier
    1>.focus.cpp(733) : error C2065: ‘x’ : undeclared identifier
    1>.focus.cpp(733) : error C2065: ‘x’ : undeclared identifier
    The code in bold is the line mentioned.

    I’m not very technically able when it comes to c++. So if your reply could be something I could copy and paste in to solve my problem that would be nice. :)

Answers

  • Hi brownie,

    What I meant with ‘for loop’ was the inner for loop in your code. ;)

    You created your inner for loop like this;

    for (int x = 0; x < width-1; ++x)   
    {  
        uc b = ScaledPixelClip(p[x*3+0] * center_weight + (bb + p[x*3+3]) * outer_weight);  
        bb = p[x*3+0]; p[x*3+0] = b;  
        uc g = ScaledPixelClip(p[x*3+1] * center_weight + (gg + p[x*3+4]) * outer_weight);  
        gg = p[x*3+1]; p[x*3+1] = g;  
        uc r = ScaledPixelClip(p[x*3+2] * center_weight + (rr + p[x*3+5]) * outer_weight);  
        rr = p[x*3+2]; p[x*3+2] = r;  
    }  
     

    In order to remove the error, you need to declare the varialbe ‘x’ outside that inner loop like this;

    int x;  
    for (x = 0; x < width-1; ++x)      
    {     
        uc b = ScaledPixelClip(p[x*3+0] * center_weight + (bb + p[x*3+3]) * outer_weight);     
        bb = p[x*3+0]; p[x*3+0] = b;     
        uc g = ScaledPixelClip(p[x*3+1] * center_weight + (gg + p[x*3+4]) * outer_weight);     
        gg = p[x*3+1]; p[x*3+1] = g;     
        uc r = ScaledPixelClip(p[x*3+2] * center_weight + (rr + p[x*3+5]) * outer_weight);     
        rr = p[x*3+2]; p[x*3+2] = r;     
    }     

    Regards,

    • Marked as answer by

      Wednesday, February 25, 2009 5:22 AM

Эта ошибка связана с отсутствием определения переделенной. Смотрим пример:

#include "stdafx.h"

int main(int argc, char* argv[])
{
	for (int x=0;x<y;x++)	//y не объявлена
	{
	}
	return 0;
}

Переменная y не определена:

D:VСTestErrorTestError.cpp(12) : error C2065: 'y' : undeclared identifier

Основа этой ошибки в том, что переменную прежде чем использовать нужно объявить. А вот почему она не объявлена, может быть много случаев. Например, перепутаны верхние — нижние индексы в названиях.

#include "stdafx.h"

int main(int argc, char* argv[])
{
	int X;		// надо бы нижнем регистром
	for (int x=0;x<y;x++)
	{
	}
	return 0;
}

Отсутствие определения функции или переменной может быть связано с отсутствием заголовочного файла.

#include "stdafx.h"

int main(int argc, char* argv[])
{
	BOOL i;
	return 0;
}

Она просто не определена в заголовочном файле:

D:VСTestErrorTestError.cpp(11) : error C2065: 'BOOL' : undeclared identifier

Она просто не определена в заголовочном файле. Надо включить windows.h и все станет на свое место.

Область видимости переменной может привести к появлению этой ошибки.

#include "stdafx.h"

int main(int argc, char* argv[])
{
	for (int x=0;x<10;x++)
	{
		for (int y=0;y<10;y++)
		{
		}
	}
	y=20;
	return 0;
}

И та же ошибка:

D:VСTestErrorTestError.cpp(15) : error C2065: 'y' : undeclared identifier

Здравствуйте. Я новичок в 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
   }
};

/*
** PlayerManager.h
*/

#include <cstdlib>
#include <ctime>
#include <math.h>
#include <vector>

#include «hge.h»
#include «hgegui.h»
#include «hgefont.h»
#include «hgecolor.h»

#include «Player.h»
//#include «ScoreManager.h»

using std::vector;

class PlayerManager
{
public:
PlayerManager(HGE *);

bool EveryMan;//is everyman for himself?
bool FourNotTwo;// 4 players not 2?

virtual void Initialize(HGE *);
virtual void Render();
virtual void Update(int,int,vector<Ball> &);
virtual void GetAllPlayerInput(HGE *);
virtual int PlayerCounter();
virtual int TeamCounter();
virtual void UpdateTeams();
virtual void SetTeam(int,int);
virtual void SetPlayers(int,int);
virtual void DeleteAllPlayer(HGE *);
virtual void DeletePlayer();
virtual float X(int);
virtual float Y(int);

private:

//to give each player the same Red texture
HTEXTURE PaddleTexR;
//to give each player the same Green texture
HTEXTURE PaddleTexG;
//to give each player the same Blue texture
HTEXTURE PaddleTexB;
//to give each player the same Yellow texture
HTEXTURE PaddleTexY;

// a vector to hold all the players info
vector<Player> AllPlayers;

//Current Number of players
int CurrentPlayers;

//Current number of Teams
int CurrentTeams;
};

/*
** PlayerManager.cpp
*/

#include «PlayerManager.h»

//creates the Player manager to handle the Player
PlayerManager::PlayerManager(HGE *_hge)
{
//current Players in game
CurrentPlayers = 0;

//Current Teams in game
CurrentTeams = 0;

//team type designator
EveryMan = true;

//players type designator
FourNotTwo = false;
}

// because we cant load textures until HGE has been initialized…so we call this little gem later.
void PlayerManager::Initialize(HGE *_hge)
{
//to give the Players all the same texture.
PaddleTexR= _hge->Texture_Load(«PaddleRed.png»);
//to give the Players all the same texture.
PaddleTexG= _hge->Texture_Load(«PaddleGreen.png»);
//to give the Players all the same texture.
PaddleTexB= _hge->Texture_Load(«PaddleBlue.png»);
//to give the Players all the same texture.
PaddleTexY= _hge->Texture_Load(«PaddleYellow.png»);
}

void PlayerManager::Render()
{
//calls render on all Players created
for(int i=0; i<PlayerCounter(); i++)
{
AllPlayers[i].Render();
}
}

void PlayerManager::Update(int ScreenWidth, int ScreenHeight, vector<Ball> & AllBalls)
{
//calls update on all Players created
for(int i=0; i<PlayerCounter(); i++)
{
AllPlayers[i].Update(AllPlayers,FourNotTwo, ScreenWidth,ScreenHeight,AllBalls);
}
}

void PlayerManager::GetAllPlayerInput(HGE *_hge)
{
//calls update on all Players created
for(int i=0; i<PlayerCounter(); i++)
{
AllPlayers[i].GetInput(_hge);
}
}

int PlayerManager::PlayerCounter()
{
//return how many Player we have
return CurrentPlayers;
}

int PlayerManager::TeamCounter()
{
//return how many Player we have
return CurrentTeams;
}

void PlayerManager::UpdateTeams()
{
//can have 2 or 4 teams
//if everyman is true
if(EveryMan)
{
//every player is on his own team
CurrentTeams = CurrentPlayers;
}
else
{
//team is forced to 2. if 2 players thats 2 teams if 4 players its team based.
CurrentTeams = 2;
}
}

void PlayerManager::SetTeam(int PlayerNum, int DesiredTeam)
{
//tell player to change to DesiredTeam
AllPlayers[PlayerNum].SetTeam(DesiredTeam);
}

void PlayerManager::SetPlayers(int ScreenWidth,int ScreenHeight)
{

if(CurrentPlayers >0)
{
for(int i=CurrentPlayers-1; i>=0; i—)
{
//calls delete on the last enterd Player
AllPlayers[i].Delete();
//removes the last Player added to the vector
AllPlayers.pop_back();
}
}

//remove all Player from the counter
CurrentPlayers= 0;

int temp =999;
//4not2 true? then 4 players
if(FourNotTwo)
{
//set up 4 players
//how many teams?
//if 2
if(!EveryMan)
{
for(int i =0; i<4; i++)
{
//increase current Player counter; for player ID use
CurrentPlayers++;

//Set that player to a team based on his ID. (CurrentPlayers%2) so even players are team 1 and odd players are team 2
temp = CurrentPlayers%2;

//swap it so that players 1 and 3 are on team 1 and players 2 and 4 are on team 1
if(temp == 0)
temp = 1;
else
temp = 0;

temp +=1;

// set up colors for paddles based on team.
switch(temp)
{
case 1:
//create a player whom will get the ID of the Currentplayers-1
AllPlayers.push_back(Player(CurrentPlayers,PaddleTexR,ScreenWidth,ScreenHeight,FourNotTwo)); break;

case 2:
//create a player whom will get the ID of the Currentplayers-1
AllPlayers.push_back(Player(CurrentPlayers,PaddleTexB,ScreenWidth,ScreenHeight,FourNotTwo)); break;
}
AllPlayers[CurrentPlayers-1].SetTeam(temp); //so teams are 1 and 2
}
}
//4 teams every man for himself
else
{
for(int i =0; i<4; i++)
{
//increase current Player counter; for player ID use
CurrentPlayers++;

//Set that player to a team based on his ID. (CurrentPlayers%4)
temp = CurrentPlayers%4;

if(temp == 0)
temp =4; // this means player 1 = team1 2= 2 3=3 4=4(not zero)

// set up colors for paddles based on team.
switch(temp)
{
case 1:
//create a player whom will get the ID of the Currentplayers-1
AllPlayers.push_back(Player(CurrentPlayers,PaddleTexR,ScreenWidth,ScreenHeight,FourNotTwo)); break;

case 2:
//create a player whom will get the ID of the Currentplayers-1
AllPlayers.push_back(Player(CurrentPlayers,PaddleTexG,ScreenWidth,ScreenHeight,FourNotTwo)); break;
case 3:
//create a player whom will get the ID of the Currentplayers-1
AllPlayers.push_back(Player(CurrentPlayers,PaddleTexB,ScreenWidth,ScreenHeight,FourNotTwo)); break;
case 4:
//create a player whom will get the ID of the Currentplayers-1
AllPlayers.push_back(Player(CurrentPlayers,PaddleTexY,ScreenWidth,ScreenHeight,FourNotTwo)); break;
}

AllPlayers[CurrentPlayers-1].SetTeam(temp);
}

}

}
//else 2 players
else
{

//set up 2 players
for(int i =0; i<2; i++)
{
//increase current Player counter; for player ID use
CurrentPlayers++;

//Set that player to a team based on his ID.
//(CurrentPlayers%2) so even players are team 1 and odd players are team 2
temp = CurrentPlayers%2;
//swap it so players are on correct team
if(temp == 0)
temp = 1;
else
temp = 0;

temp+=1;

switch(temp)
{
case 1:
//create a player whom will get the ID of the Currentplayers-1
AllPlayers.push_back(Player(CurrentPlayers,PaddleTexR,ScreenWidth,ScreenHeight,FourNotTwo)); break;
case 2:
//create a player whom will get the ID of the Currentplayers-1
AllPlayers.push_back(Player(CurrentPlayers,PaddleTexB,ScreenWidth,ScreenHeight,FourNotTwo)); break;
}

//add one to team number to state teams are 1 and 2
AllPlayers[CurrentPlayers-1].SetTeam(temp);
}
}
}

void PlayerManager::DeleteAllPlayer(HGE *_hge)
{
for(int i=CurrentPlayers-1; i>=0; i—)
{
//calls delete on the last enterd Player
AllPlayers[i].Delete();
//removes the last Player added to the vector
AllPlayers.pop_back();
}

//remove all Player from the counter
CurrentPlayers= 0;
_hge->Texture_Free(PaddleTexR);
_hge->Texture_Free(PaddleTexG);
_hge->Texture_Free(PaddleTexB);
_hge->Texture_Free(PaddleTexY);
}

void PlayerManager::DeletePlayer()
{
//calls delete on the last enterd Player
AllPlayers[CurrentPlayers-1].Delete();
//removes the last Player added to the vector
AllPlayers.pop_back();
//remove a Player from the counter
CurrentPlayers—;
}

float PlayerManager::X(int ID)
{
//return a given Player X pos
return AllPlayers[ID].GetX();
}

float PlayerManager::Y(int ID)
{
//return a given ball Y pos
return AllPlayers[ID].GetY();
}

Что такое необъявленные ошибки идентификатора? Каковы общие причины и как их исправить?

Пример текстов ошибок:

  • Для компилятора Visual Studio: error C2065: 'cout' : undeclared identifier
  • Для компилятора GCC: 'cout' undeclared (first use in this function)

39

Решение

Чаще всего они приходят из-за того, что забывают включить заголовочный файл, содержащий объявление функции, например, эта программа выдаст ошибку «необъявленный идентификатор»:

Отсутствует заголовок

int main() {
std::cout << "Hello world!" << std::endl;
return 0;
}

Чтобы это исправить, мы должны включить заголовок:

#include <iostream>
int main() {
std::cout << "Hello world!" << std::endl;
return 0;
}

Если вы написали заголовок и включили его правильно, заголовок может содержать неправильный включить охрану.

Чтобы узнать больше, смотрите http://msdn.microsoft.com/en-us/library/aa229215(v=vs.60).aspx.

Переменная с ошибкой

Другой распространенный источник ошибки новичка возникает, когда вы неправильно написали переменную:

int main() {
int aComplicatedName;
AComplicatedName = 1;  /* mind the uppercase A */
return 0;
}

Неправильный объем

Например, этот код выдаст ошибку, потому что вам нужно использовать std::string:

#include <string>

int main() {
std::string s1 = "Hello"; // Correct.
string s2 = "world"; // WRONG - would give error.
}

Использовать до объявления

void f() { g(); }
void g() { }

g не был объявлен до его первого использования. Чтобы это исправить, либо переместите определение g до f:

void g() { }
void f() { g(); }

Или добавить декларацию g до f:

void g(); // declaration
void f() { g(); }
void g() { } // definition

stdafx.h не сверху (специфично для VS)

Это зависит от Visual Studio. В VS нужно добавить #include "stdafx.h" перед любым кодом. Код до того, как он игнорируется компилятором, так что если у вас есть это:

#include <iostream>
#include "stdafx.h"

#include <iostream> будет проигнорировано Вам нужно переместить его ниже:

#include "stdafx.h"#include <iostream>

Не стесняйтесь редактировать этот ответ.

54

Другие решения

Рассмотрим похожую ситуацию в разговоре. Представьте, что ваш друг говорит вам: «Боб идет на ужин», а ты не представляешь, кто такой Боб. Вы будете в замешательстве, верно? Твой друг должен был сказать: «У меня есть коллега по работе по имени Боб. Боб подходит к обеду». Теперь Боб объявлен, и вы знаете, о ком говорит ваш друг.

Компилятор выдает ошибку «необъявленный идентификатор», когда вы пытаетесь использовать какой-то идентификатор (который будет именем функции, переменной, класса и т. Д.), И компилятор не видит объявления для него. То есть компилятор понятия не имеет, о чем вы говорите, потому что раньше его не видел.

Если вы получаете такую ​​ошибку в C или C ++, это означает, что вы не сказали компилятору о том, что вы пытаетесь использовать. Объявления часто встречаются в заголовочных файлах, поэтому, скорее всего, это означает, что вы не включили соответствующий заголовок. Конечно, может случиться так, что вы просто не помните, чтобы объявить сущность вообще.

Некоторые компиляторы выдают более конкретные ошибки в зависимости от контекста. Например, пытаясь скомпилировать X x; где тип X не был объявлен с Clang скажет вам «неизвестное имя типа X«. Это гораздо полезнее, потому что вы знаете, что он пытается интерпретировать X как тип. Тем не менее, если у вас есть int x = y;, где y еще не объявлено, он скажет вам «использование необъявленного идентификатора y«потому что есть некоторая двусмысленность в том, что именно y может представлять.

12

У меня была такая же проблема с пользовательским классом, который был определен в пространстве имен. Я пытался использовать класс без пространства имен, вызывая ошибку компилятора «идентификатор» MyClass «не определен».
Добавление

using namespace <MyNamespace>

или используя класс, как

MyNamespace::MyClass myClass;

решил проблему.

5

В C и C ++ все имена должны быть объявлены перед использованием. Если вы попытаетесь использовать имя переменной или функции, которая не была объявлена, вы получите ошибку «необъявленный идентификатор».

Однако функции — это особый случай в C (и только в C), в котором вам не нужно сначала объявлять их. Компилятор C будет предполагать, что функция существует с числом и типом аргументов, как в вызове. Если фактическое определение функции не совпадает, вы получите еще одну ошибку. Этот особый случай для функций не существует в C ++.

Вы исправляете ошибки такого рода, проверяя, что функции и переменные объявлены до их использования. В случае printf вам нужно включить заголовочный файл <stdio.h> (или же <cstdio> в C ++).

Для стандартных функций я рекомендую вам проверить, например, этот справочный сайт, и найдите функции, которые вы хотите использовать. Документация для каждой функции говорит вам, какой заголовочный файл вам нужен.

4

Эти сообщения об ошибках

1.For the Visual Studio compiler: error C2065: 'printf' : undeclared identifier
2.For the GCC compiler: `printf' undeclared (first use in this function)

означает, что вы используете имя printf но компилятор не видит, где было объявлено имя, и, соответственно, не знает, что это значит.

Любое имя, используемое в программе, должно быть объявлено до ее использования. Компилятор должен знать, что обозначает имя.

В этом конкретном случае компилятор не видит объявление имени printf , Как мы знаем (но не компилятор) это имя стандартной функции C, объявленной в заголовке <stdio.h> в C или в заголовке <cstdio> в C ++ и размещены в стандарте (std::) и глобальный (::) (не обязательно) пространства имен.

Поэтому, прежде чем использовать эту функцию, мы должны предоставить объявление ее имени компилятору путем включения соответствующих заголовков.

Например
C:

#include <stdio.h>

int main( void )
{
printf( "Hello Worldn" );
}

C ++:

#include <cstdio>

int main()
{
std::printf( "Hello Worldn" );
// or printf( "Hello Worldn" );
// or ::printf( "Hello Worldn" );
}

Иногда причиной такой ошибки является простая опечатка. Например, давайте предположим, что вы определили функцию PrintHello

void PrintHello()
{
std::printf( "Hello Worldn" );
}

но в основном вы сделали опечатку и вместо PrintHello ты напечатал printHello с строчной буквы «р».

#include <cstdio>

void PrintHello()
{
std::printf( "Hello Worldn" );
}

int main()
{
printHello();
}

В этом случае компилятор выдаст такую ​​ошибку, потому что он не видит объявление имени printHello, PrintHello а также printHello два разных имени, одно из которых было объявлено, а другое не объявлено, но используется в теле основного

3

Это похоже на использование функции без ее объявления. заголовочный файл будет содержать
функция printf (). Включите заголовочный файл в вашу программу, это решение для этого.
Некоторые пользовательские функции могут также вызывать ошибки, если они не были объявлены перед использованием. Если
это используется во всем мире без проб.

0

В большинстве случаев, если вы уверены, что импортировали данную библиотеку, Visual Studio поможет вам с IntelliSense.

Вот что сработало для меня:

Удостоверься что #include "stdafx.h" объявляется первым, то есть вверху всех ваших включений.

0

Понравилась статья? Поделить с друзьями:
  • Error c2065 cout undeclared identifier
  • Error c2065 cin
  • Error c2064 term does not evaluate to a function taking 1 arguments
  • Error c2062 тип float не требуется
  • Error c2061 синтаксическая ошибка идентификатор string