简体   繁体   English

c++ 中的 class 出现问题

[英]Having trouble with class in c++

I'm obviously making a mistake here, but please help me.我显然在这里犯了一个错误,但请帮助我。

#include <iostream>
#include <string>

using namespace std;

int main()
{
    class Item
    {
       int Value;
       int Use_On(Entity Target)
       {
            Target.HP += Value;
        }
    };

    class Entity
    {
        int HP;
        Item Slot;
    };
}

The Item class have a function that change the HP value of an Entity object, and the Entity class have an Item object. The Item class have a function that change the HP value of an Entity object, and the Entity class have an Item object. This result in an error because Entity wasn't declared yet.这会导致错误,因为尚未声明实体。 I've tried to make a prototype of the Entity class and declare it before the Item class, but this just result in another error saying Entity is an incomplete type.我试图制作实体 class 的原型并在项目 class 之前声明它,但这只会导致另一个错误,即实体是不完整的类型。 How can I solve this?我该如何解决这个问题? Also, sorry for the title, I'm not really good at english:|另外,对不起标题,我不太擅长英语:|

The solution is to forward-declare the class, declare the class method first, and define it only after all classes have been declared.解决方法是前向声明class,先声明class方法,等所有类都声明完后再定义。

class Entity;

class Item
{
    int Value;
    int Use_On(Entity Target);
};

class Entity
{
    int HP;
    Item Slot;
};

int Item::Use_On(Entity Target)
{
    Target.HP += Value;
}

See your C++ textbook for a complete discussion and explanation of forward reference, and the details of the alternative ways to declare and define class methods.有关前向引用的完整讨论和解释,以及声明和定义 class 方法的替代方法的详细信息,请参阅您的 C++ 教科书。

This should solve the immediate compilation error, but there are multiple other problems with the shown code that you will need to fix.这应该可以解决立即的编译错误,但是您需要修复显示的代码的多个其他问题。

  1. Use_On is declared as returning an int , but does not return anything. Use_On被声明为返回int ,但不返回任何内容。

  2. In C++ parameters get passed by value by default, which means that Use_On ends up modifying only its local parameter, and otherwise accomplishing absolutely nothing, whatsoever.在 C++ 中,参数默认按值传递,这意味着Use_On最终只修改其本地参数,否则一无所获。 Whatever object gets passed into this class method remains completely unchanged.无论 object 传递到此 class 方法中,都保持完全不变。 You will need to change the code to pass the parameter either via a pointer or by reference.您将需要更改代码以通过指针或引用传递参数。 Your C++ textbook will also have a discussion on these topics.您的 C++ 教科书也将对这些主题进行讨论。

  3. Classes should be declared in global scope, instead of inside functions like main() , where some class features are not available.类应该在全局 scope 中声明,而不是像main()这样的内部函数,其中一些 class 功能不可用。

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

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