"表达式必须具有类类型"错误是什么意思?

Rob*_*lin 3 c++ arrays

#include <cstdlib>
using namespace std;

int main()
{
    int arrayTest[512];
    int size = arrayTest.size();
    for(int a = 0;a<size;a++)
    {
         //stuff will go here
    }
}
Run Code Online (Sandbox Code Playgroud)

我在这里做错了什么,因为计划是用一些数字填充数组

Naw*_*waz 10

做这个:

int arrayTest[512];
int size = sizeof(arrayTest)/sizeof(*arrayTest);
Run Code Online (Sandbox Code Playgroud)

C风格的数组没有成员函数.他们没有任何阶级观念.

无论如何,更好地使用std::array:

#include <array>

std::array<int,512> arrayTest;
int size = arrayTest.size();   //this line is exactly same as you wrote!
Run Code Online (Sandbox Code Playgroud)

看起来像你想要的.现在你可以使用索引i来访问的元素arrayTest作为arrayTest[i]其中i可以从变化0size-1(含).


Sha*_*our 5

arrayTest 不是一个类或结构,而是一个数组,它没有成员函数,在这种情况下,这将获得数组的大小:

size_t size = sizeof(arrayTest)/sizeof(int);
Run Code Online (Sandbox Code Playgroud)

尽管如果您的编译器支持C++11,那么使用std::array会更好:

#include <array>

std::array<int,512> arrayTest ;
size_t size = arrayTest.size() ;
Run Code Online (Sandbox Code Playgroud)

正如上面链接的文档所示,您还可以使用 range for 循环来迭代std::array的元素:

for( auto &elem : arrayTest )
{
   //Some operation here
}
Run Code Online (Sandbox Code Playgroud)