视觉 为什么这个 C++ 代码不能编译?

visual Why won't this c++ code compile?

本文关键字:不能 编译 代码 C++ 为什么 视觉      更新时间:2023-10-16

考虑到我是c++新手,我想我会尝试编写一个非常简单的控制台应用程序,填充2d数组并显示其内容。

但是我写的代码无法编译。

我得到的一些错误是:

error C2065: 'box':未声明的标识符
错误C2228: left of '。GenerateBox'必须有class/struct/union

下面是我的代码:
#include <iostream>
using namespace std;
int main()
{
  Box box;
  box.GenerateBox();
}
class Box
{
private:
  static int const maxWidth = 135;
  static int const maxHeight = 60; 
  char arrTest[maxWidth][maxHeight];
public:
    void GenerateBox()
    {
      for (int i=0; i<maxHeight; i++)
        for (int k=0; k<maxWidth; k++)
        {
          arrTest[i][k] = 'x';
        }
      for (int i=0; i<maxHeight; i++)
      {
        for (int k=0; k<maxWidth; k++)
        {
          cout << arrTest[i][k];
        }
           cout << "n";
      }
    }
};

你知道是什么导致了这些错误吗?

c++编译器从上到下一次读取源文件。您已经在底部描述了Box类,在main()之后,在尝试使用该类的部分之后。因此,当编译器到达你说'Box Box;'的部分时,它还没有看到类定义,因此不知道'Box'是什么意思。

main函数移动到代码的底部。具体来说,您需要在引用Box之前定义它。

唯一的时候,你可以摆脱只有一个前向声明(即class Box;)是当你只是使用Box作为一个指针或引用。

您必须在使用Box之前定义它。因此,对于您的小测试,您可以将类定义放在main之前。

对于较大的程序,您将把类定义放在.h头文件中,这些头文件将包含在源文件的顶部。

是由于main()的预先声明。在Box类声明后使用main

@nikko是对的。您必须在使用Box类之前声明它。通过

  • 剪切粘贴声明
  • 或告诉编译器您将稍后声明它们

试试这个
extern class Box;
//use box class here
//then define it later as you wish