error: 'x' does not name a type

China☆狼群 提交于 2021-02-07 20:54:12

问题


When I try to declare an instance of my class 'Game' I receive the compile error "error: 'Game' does not name a type" for main.cpp.

If probably doesn't matter but i'm using codeblocks.

Relevant code from Game.cpp

#include "../include/main.h"

class Game
{
    private:

    public:
};

Relevant code from Main.cpp

#include "../include/main.h"

Game g; //this is the line it is referring to

int main(int argc, char* args[])
{
    return 0;
}

I'm only starting to learn c++ so i probably overlooked something obvious :(


回答1:


Include the declaration for "Game" in a header

notepad main.h =>

#ifndef MAIN_H
#define MAIN_H

class Game
{
    private:
      ...
    public:
      ...
};
#endif
// main.h

notepad main.cpp =>

#include "main.h"

Game g; // We should be OK now :)

int 
main(int argc, char* args[])
{
    return 0;
}

gcc -g -Wall -pedantic -I../include -o main main.cpp

Note how you:

1) Define your classes (along with any typedefs, constants, etc) in a header

2) #include the header in any .cpp file that needs those definitions

3) Compile with "-I" to specify the directory (or directories) containing your headers

'Hope that helps




回答2:


C file or cpp file is a matter of multiple errors occurring is compiled.

The header file for each

 # pragma once 
 Or
 # Ifndef __SOMETHING__ 
 # define __SOMETHING__

 Add the code ...

 # Endif



回答3:


Maybe you can remove the Game class declaration in Game.cpp and try to create another file named "Game.h" under ../inclue/ like:

#ifndef _GAME_H_
#define _GAME_H_

class Game
{
    private:
    public:
};

#endif

and include this Header file in Main.cpp. Then I think the error won't happen:)

Because we usually use .cpp file for class definition and .h file for declaration, then include .h file in Main.cpp.



来源:https://stackoverflow.com/questions/8470822/error-x-does-not-name-a-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!