简体   繁体   English

C ++错误:标识符“类名”未定义

[英]C++ Error: identifier 'class name' is undefined

I have just started to use classes in C++. 我刚刚开始在C ++中使用类。 As a first object-oriented project, I want to program a character creator for a Pen and Paper game. 作为第一个面向对象的项目,我想编写一个用于Pen and Paper游戏的角色创建程序。

I have created the class structure including inheritance. 我创建了包括继承的类结构。

This is an example class: 这是一个示例类:

#include "Characters.cpp"
#include "Fighter.cpp"
#include "Dwarf.cpp"

class FighterDwarf : public Characters, public Fighter, public Dwarf {

public:
    string test = "Hello, I am a fighter dwarf!";

    void testPrint() {
        cout << test << endl;
    }

    FighterDwarf() {

    }
};

And here is main: 这是主要的:

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    FighterDwarf fighterDwarf;
    fighterDwarf.testPrint();
    return 0;
}

In case it is not obvious, they are in two different files/Items. 如果不太明显,它们位于两个不同的文件/项目中。 I don't think it is important but they are also in two different folders. 我认为这并不重要,但它们也位于两个不同的文件夹中。

The problem is that I get the error message "Error: identifier "FighterDwarf" is undefined. 问题是我收到错误消息“错误:标识符“ FighterDwarf”未定义。

It is most likely a beginner mistake. 这很可能是初学者的错误。 I would guess that I must somehow declare "FighterDwarf" in the main file before I can create an instance of the class. 我猜想我必须以某种方式在主文件中声明“ FighterDwarf”,然后才能创建该类的实例。 If this is the case, I don't know how to do that with classes. 如果是这种情况,我不知道该如何使用类。

By they way, I know that there are a lot of people out there not liking multiple inheritance but I have chosen to use C++ and not Java because of that very feature. 顺便说一句,我知道有很多人不喜欢多重继承,但是由于这个功能,我选择使用C ++而不是Java。

SOLVED: If I want to do everything in a single file, I need to do that in the header. 解决:如果我想在一个文件中完成所有操作,则需要在标题中执行。 Which I will, as some of the classes have some more code which I don't want to rewrite right now. 我会的,因为有些类还有更多我现在不想重写的代码。 Furthermore, I find it easier tow work with one file than two, at least at the beginning where I have more important things to mind. 此外,我发现使用一个文件比使用两个文件更容易,至少在起初我要记住的是重要的事情。 But I will split the classes up into two in my very next program. 但是我将在下一个程序中将这些类分为两个类。 By the way, why is it so important to split classes up? 顺便说一句,为什么分类很重要? Isn't it easier to work with one class? 上一堂课不是容易吗?

It has nothing to do with classes. 它与类无关。 Your main.cpp file simply needs to #include the header file which declares and/or defines your FighterDwarf class. 您的main.cpp文件只需要#include头文件 ,即可声明和/或定义FighterDwarf类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM