【问题标题】:Error: variable or field 'PrintEntity' declared void void PrintEntity(Entity e);错误:变量或字段“PrintEntity”声明为 void void PrintEntity(Entity e);
【发布时间】:2019-10-16 10:22:33
【问题描述】:

代码真的很简单(但我是新手,所以我不知道我做错了什么):

#include<iostream>
#include<string>

void PrintEntity(Entity* e);

class Entity
{
  public:
      int x,y;


      Entity(int x, int y)
      {

         Entity* e= this;
         e-> x=x;
         this->y=y;

         PrintEntity(this);

      }

  };

void PrintEntity(Entity* e)
  {
    // *Do stuff*
  }

int main()
  {

     return 0;
  }

我对错误的理解是我不能在之前声明函数PrintEntity 类实体。但即使我在类下面声明函数也会有问题,因为在构造函数中我调用的是函数 PrintEntity。

所以我很困惑。谁能向我解释一下我做错了什么?

【问题讨论】:

    标签: c++ function class this declaration


    【解决方案1】:

    在类定义之前声明函数

    void PrintEntity( class Entity* e);
    

    使用详细的类型说明符。

    否则编译器不知道Entity是什么。

    【讨论】:

      【解决方案2】:

      编译器自上而下读取您的文件。

      遇到void PrintEntity(Entity * e);时,必须判断Entity * e是形参(使其成为函数声明)还是乘法(使其成为带初始化器的变量声明)。

      由于编译器完全不知道一个名为“Entity”的类型,它决定这必须是一个变量声明,并且一个变量不能有类型void

      解决办法是在函数原型之前声明类,或者单独声明:

      class Entity;
      void PrintEntity(Entity* e);
      

      或直接在函数声明中:

      void PrintEntity(class Entity* e);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-16
        • 1970-01-01
        • 2021-12-20
        相关资源
        最近更新 更多