视觉 为什么这个 C++ 代码不能编译?
visual Why won't this c++ code compile?
考虑到我是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
相关文章:
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么使用 std::vector 的代码不能编译,但使用 std::unique_ptr 如果没有 noexcept
- 为什么我不能编译这个在Cygwin的Visual Studio中编写的C++文件?
- 为什么我不能编译这个简单的线程测试?
- 为什么 --string::end() 可以编译,而 --string.size() 不能编译?
- 为什么G 5.4不能编译此编译时质数代码
- 为什么最简单的模板模板不能编译
- 为什么这个 c++ 代码不能编译?
- 为什么我不能编译这个开源项目
- 为什么 g++ 不能编译一个简单的 GTK 程序?
- C++。为什么我不能编译此代码?使用const_cast去除恒常性有什么问题?
- 为什么这个模板函数不能编译C++
- 托管类型的成员函数不能编译为非托管函数
- 为什么这个简单的C++程序不能编译?
- 为什么这个C++代码不能编译
- 为什么没有enable_if就不能编译
- 使用重载的operator=不能编译
- CodeRunner——不能编译多个源c++程序
- 为什么[]可变{}不能编译
- 为什么自建的g++编译器不能编译我的代码