description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid |
---|---|---|---|---|---|
Learn more about: Compiler Error C2079 |
Compiler Error C2079 |
11/04/2016 |
C2079 |
C2079 |
ca58d6d5-eccd-40b7-ba14-c003223c5bc7 |
Compiler Error C2079
‘identifier’ uses undefined class/struct/union ‘name’
The specified identifier is an undefined class, structure, or union.
This error can be caused by initializing an anonymous union.
The following sample generates C2079:
// C2079.cpp // compile with: /EHsc #include <iostream> int main() { std::ifstream g; // C2079 }
Possible resolution:
// C2079b.cpp // compile with: /EHsc #include <fstream> int main( ) { std::ifstream g; }
C2079 can also occur if you attempt to declare an object on the stack of a type whose forward declaration is only in scope.
// C2079c.cpp class A; class B { A a; // C2079 }; class A {};
Possible resolution:
// C2079d.cpp // compile with: /c class A; class C {}; class B { A * a; C c; }; class A {};
Think about the computer’s memory for a second here.
class B;
class A {
byte aa;
B ab;
};
class B {
byte bb;
A ba;
};
A x;
Now the question the compiler needs to answer is How much space should I reserve for x
?
Let’s see. The first byte of x
is byte aa;
. Easy enough. That’s 1 byte.
Next comes B ab;
. Let’s see what’s in there.
The first byte of x.ab
is a byte bb;
. That’s 2 bytes for x
so far.
Next, is a A ba;
. Let’s see what’s in there.
The first byte of x.ab.ba
is a byte aa;
. That’s 3 bytes for x
so far.
And so on and so forth ad infinitum.
How big is x
? The correct answer is of course *** OUT OF CHEESE ERROR ***
.
The compiler doesn’t actually do this because it knows it can’t handle this case — so the syntax doesn’t allow circular containment in the first place.
Here’s a diagram of the contents of x
in this example:
UPDATE
Apparently, I forgot to include a solution here. Now that you understand what the problem is, the solution should be pretty simple. Use pointers. Either use a pointer from A
to B
and let B
include A
as it already does, or vice versa, or use two pointers. Then, you won’t have circular inclusion — if B
doesn’t include a copy of A
but just a pointer to it, that fixes the entire issue here.
- Remove From My Forums
-
Question
-
Good Morning all,
I encountered a compiler error c2079 which said «use of undefined class/struc/union name» and am not sure how to solve it. The following is a simplified setup of classes inside my code:
class a;
class b {
int b1;
public :
func1();
}
b::func1()
{
a aclass;
aclass.a1() <== this is where error c2079 come from. a1 is a public function of class a
}
I search Microsoft C++ compiler error web. It suggests that using pointer to a, instead of instance of a. So I changed
a aclass to a * aclass = NULL;
and
aclass.a1() to aclass->a1();
The compiler error changed to c2027 : use of undefined type ‘a’
Any suggestions? Thanks for your help.
Tom Lin
Answers
-
I would suggest to split class interface (to be put in .h files) from class implementation (to be put in .cpp file).
So, you should have 4 files:
ClassA.h (header containing interface of class A)
ClassA.cpp (implementation of class A)
ClassB.h (header containing interface of class B)
ClassB.cpp (implementation of class B)
The implementation of B::func1 method should be put in ClassB.cpp file.
The implementation of A::a1 method should be put in ClassA.cpp file.
At the beginning of ClassB.cpp file, you should add a #include «ClassA.h» because you are using class A.
See if this helps…
Giovanni
-
Marked as answer by
Thursday, May 6, 2010 6:41 PM
-
Marked as answer by
- Forum
- General C++ Programming
- error C2079: … uses undefined struct .
error C2079: … uses undefined struct …
Long code short:
|
|
Gives an error:
error C2079: ‘Combat::enemy’ uses undefined struct ‘Enemy’
Where is the problem?
Which line?
You’re missing semicolons after the class declarations.
|
|
Hmm that was just a mockup. I fixed those semicolons and it seems problem wasnt there. Error was at line 13, Enemy enemy
Edit: I guess i’ll post whole thing when i get back to my computer
Last edited on
Are these in separate files?
Yes
Can you show which classes are in which headers and how each implementation #includes them?
Yeah. I’ve cut some parts a bit but it should do:
|
|
|
|
|
|
|
|
|
|
Last edited on
I dont’ see it directly, but I’m willing to bet you have a circular inclusion problem. You appear to be just including all headers willy-nilly. Long story short, combat.h is including enemy.h, which is including some other header that includes enemy.h. The circular inclusion means that your Combat class is being defined before your Enemy class is.
Only include headers you need. See sections 4 and 5 of this article:
http://www.cplusplus.com/forum/articles/10627/#msg49679
Topic archived. No new replies allowed.
iRomul 160 / 101 / 14 Регистрация: 17.10.2012 Сообщений: 488 |
||||||||
1 |
||||||||
19.12.2015, 23:56. Показов 1223. Ответов 4 Метки c++, c2079, class (Все метки)
Приветствую. Ситуация следующая — есть 2 класса, оба используют друг друга. При компиляции вылезает ошибка: Код C2079 "MiniPlayer::music" использует неопределенный class "MiniMusic" Файл MiniPlayer.h (класс MiniPlayer — синглтон)
Файл MiniMusic.h
Что я упустил?
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
19.12.2015, 23:56 |
Ответы с готовыми решениями: Структура: error C2079: «A::myElem» использует неопределенный struct «A::B» struct A::B В зависимости от времени года «весна», «лето», «осень», «зима» определить погоду «тепло», «жарко», «холодно», «очень холодно» Исправить ошибку в строках «case 3:zadacha(Uch,Pr,Ocen);break;» и » return 0;» Исправить ошибку:error C2678: бинарный «>>»: не найден оператор, принимающий левый операнд типа «std::istream» 4 |
265 / 165 / 56 Регистрация: 25.02.2015 Сообщений: 435 |
|
20.12.2015, 00:01 |
2 |
странно. вроде нужный инклуд есть. попробуйте строчку 7 в миниплейере закоментировать.
1 |
335 / 183 / 80 Регистрация: 22.08.2013 Сообщений: 724 |
|
20.12.2015, 00:05 |
3 |
MiniMusic music; //<———- Ошибка вылезает здесь Замени на указатель, как сделал в MiniMusic. Добавлено через 1 минуту
Похоже что в MiniMusic.h не надо инклудить миниплеер. там форворд декларации достаточно.
1 |
iRomul 160 / 101 / 14 Регистрация: 17.10.2012 Сообщений: 488 |
||||
20.12.2015, 01:41 [ТС] |
4 |
|||
Perfilov, nord_v, Благодарю, теперь заработало. Добавлено через 11 минут Код C2027 использование неопределенного типа "MiniPlayer" Выглядит это так:
Добавлено через 8 минут
0 |
335 / 183 / 80 Регистрация: 22.08.2013 Сообщений: 724 |
|
20.12.2015, 01:46 |
5 |
bool onGetData(sf::SoundStream::Chunk& data) override { В классе оставь прототип, реализацию вниз кода убери. Добавлено через 3 минуты
p->next(); Тут, через указатель, вызывается метод класса MiniPlayer, а значит компилятор должен в этом месте видеть, что это за метод (форвард-декларации для этого недостаточно).
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
20.12.2015, 01:46 |
Помогаю со студенческими работами здесь Error C2664: atoi: невозможно преобразовать параметр 1 из «_TCHAR *» в «const char *» Как исправить эту ошибку в коде? #define _XOPEN_SOURCE 500 #include <conio.h> Для каждой строки найти слова, которые не имеют ни одного из букв: «l», «k», «r», «s» i «j» Выдает ошибку «использована неинициализированная локальная переменная «flag» » и с переменной «sum_check» та же проблема #include "func.h" //Функция, которая… Реализовать классы «Воин», «Пехотинец», «Винтовка», «Матрос», «Кортик» (наследование) Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 5 |
- Remove From My Forums
-
Question
-
I am porting an application from VC6 to VS2015. when I am building after including all the header files I am getting the following error
Error C2079 ‘IDBConnection’ uses undefined class ‘MIDBODBC::__MIDBODBC_EXPORT_MODE__’
I have included the header file.. but still I get this.
The class where IDBConnection is declared is like this:
namespace MIDBODBC
{class __MIDBODBC_EXPORT_MODE__ IDBConnection : public CObject
{
protected :
CDatabase* m_pDBPtr;
CMIPLOG m_pLog;
int m_nDBConnectionIndex;
int m_nDBPoolWorkerIndex;…..
…..
}
Can someone pl suggest how to tackle this error
-
Changed type
Friday, January 31, 2020 3:56 PM
Question -
Moved by
Xingyu ZhaoMicrosoft contingent staff
Tuesday, February 4, 2020 1:29 AM
-
Changed type