错误:'x'不是一种类型。

3

当我尝试声明一个名为“Game”的类实例时,我收到了编译错误“error: 'Game' does not name a type”(错误:'Game'未命名类型)的主要.cpp文件。

可能并不重要,但我正在使用Codeblocks。

来自Game.cpp的相关代码

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

class Game
{
    private:

    public:
};

Main.cpp中相关的代码:

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

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

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

我只是开始学习C++,所以可能忽略了一些显而易见的东西:(


在你的 Main.cpp 中,你没有包含类 'Game' 的定义,因此你应该在一个像 Game.h 这样的文件中定义你的类 Game,并在你的 Main.cpp 中添加 #include "Game.h"。 - Michael Bai
3个回答

3
在头文件中包含“Game”的声明。
使用记事本打开main.h文件。
#ifndef MAIN_H
#define MAIN_H

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

使用记事本打开 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

请注意以下几点:

1)在头文件中定义类(以及任何typedefs、常量等)

2)在需要这些定义的任何.cpp文件中#include头文件

3)使用"-I"选项编译,以指定包含头文件的目录(或目录)

希望这可以帮到你


0
也许你可以在Game.cpp中删除Game类的声明,然后尝试在../include/下创建另一个名为"Game.h"的文件。
#ifndef _GAME_H_
#define _GAME_H_

class Game
{
    private:
    public:
};

#endif

在Main.cpp文件中包含这个头文件,我认为错误就不会发生了:)

因为我们通常使用.cpp文件进行类定义,而.h文件用于声明,然后在Main.cpp中包含.h文件。


0

C文件或cpp文件编译时会出现多个错误的问题。

每个文件都需要相应的头文件。

 # pragma once 
 Or
 # Ifndef __SOMETHING__ 
 # define __SOMETHING__

 Add the code ...

 # Endif

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接