简体   繁体   English

如果尝试在另一个文件中声明数组,则cpp错误

[英]cpp error if trying to declare an array in another file

I wanted to make my code more clear - this is why I made an extra cpp file where I declared an array which is taking a lot of space. 我想使代码更清晰-这就是为什么我制作了一个额外的cpp文件,在其中声明了占用大量空间的数组的原因。

But whenever I try to compile my code it says 但是每当我尝试编译我的代码时,它都会说

error c2466: Assignment of an array of constant size can not be 错误c2466:不能分配恒定大小的数组

(I translated from German, so don't wonder if you don't know this error 1by1) (我是从德语翻译过来的,所以请不要怀疑您是否不知道此错误1by1)

The code in main.cpp (To include the file) main.cpp的代码(包含文件)

#include "mapOne.cpp"

And the code in mapOne.cpp : 以及mapOne.cpp的代码:

int point[100][100][2];
point [1][0][0] = 1; [...]

Can someone help me? 有人能帮我吗? I hate it, if a file is >400 lines long just because there is one array declared... 我讨厌它,如果文件的长度大于400行,仅仅是因为声明了一个数组...

You're trying to assign values to your array outside of a function, which isn't allowed. 您正在尝试向函数外部的数组分配值,这是不允许的。 Instead, the compiler assumes you're trying to declare a new array. 相反,编译器假定您正在尝试声明一个新数组。

Try wrapping the assignments in a function, and call that function before you start using the array. 尝试将分配包装在函数中,并在开始使用数组之前调用该函数。

The problem you have is happening because you didn't declare the array in an area where your function will be able to use it from. 您发生的问题是因为您没有在函数可以从中使用数组的区域中声明数组。 For instance, If I do the following code: 例如,如果我执行以下代码:

In file1.cpp 在file1.cpp中

int array[20];

In file2.cpp 在file2.cpp中

#include "file1.cpp"

int function1()
{
  i = 1;
  for (int x = 0; x<20; x++)
  {
    array[x] = i;
    i = i + 2;
  }
}

The array[x] would not be recognized. 无法识别array [x]。 The reason it is not recognized is because even if you use the "include" code on top, you are only including the ability to use the functions that are present in the file1.cpp file. 无法识别它的原因是,即使您在顶部使用“ include”代码,也仅包含使用file1.cpp文件中存在的功能的能力。 The reason you are only allowed to use the functions and not the variables is simply because the compilers don't want to mix the variables you declare in file1.cpp and file2.cpp. 只允许使用函数而不使用变量的原因仅是因为编译器不想混合您在file1.cpp和file2.cpp中声明的变量。 This makes sense because a lot of times you'll declare variables of the same name in different files because it is simpler. 这很有意义,因为很多时候您会在不同文件中声明相同名称的变量,因为它更简单。

What you can do however is declare the array in a header file. 但是,您可以在头文件中声明该数组。 If your writing your function in file2.cpp, you create a header file called file2.h: 如果在file2.cpp中编写函数,则会创建一个名为file2.h的头文件:

In file2.h: 在file2.h中:

class file2
{
    public:
    int array[20];///or whichever type of array you want to declare

}

It is important you keep the variables under the "public:" section so that all the functions you make in the file2.cpp can use it. 重要的是,将变量保留在“ public:”部分下,以便您在file2.cpp中创建的所有函数都可以使用它。

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

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