错误是什么意思"expression must have class type"?

What does "expression must have class type" error mean?

本文关键字:class type have expression 是什么 意思 错误 must      更新时间:2023-10-16
#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
    }
}

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

这样做:

int arrayTest[512];
int size = sizeof(arrayTest)/sizeof(*arrayTest);

C 样式数组没有成员函数。他们没有任何阶级概念。

无论如何,最好使用std::array

#include <array>
std::array<int,512> arrayTest;
int size = arrayTest.size();   //this line is exactly same as you wrote!

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

arrayTest不是

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

size_t size = sizeof(arrayTest)/sizeof(int);

虽然如果你的编译器支持 C++11 而不是使用 std::array 会更好:

#include <array>
std::array<int,512> arrayTest ;
size_t size = arrayTest.size() ;

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

for( auto &elem : arrayTest )
{
   //Some operation here
}

数组没有成员。您必须使用类似以下内容:

int size = sizeof(arrayTest) / sizeof(arrayTest[0]);

更好的是,如果您必须使用普通数组而不是std::array,请使用辅助函数。这也具有在指针而不是数组上尝试时不会中断的优点:

template<int N, typename T> int array_size(T (&)[N]) {return N;}
int size = array_size(arrayTest);

如果你被数组困住了,你可以定义你的getArraySize函数:

template <typename T,unsigned S> 
inline unsigned getArraySize(const T (&v)[S]) { return S; } 

在这里看到: http://www.cplusplus.com/forum/general/33669/#msg181103

std::array仍然是更好的解决方案。