What does “expression must have class type” error

2020-07-22 09:39发布

#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
    }
}

What am I doing wrong here becuase the plan is to just fill the array with some numbers

标签: c++ arrays
4条回答
仙女界的扛把子
2楼-- · 2020-07-22 10:07

Do this:

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

C-style arrays don't have member function. They don't have any notion of class.

Anyway, better use std::array:

#include <array>

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

which looks like what you wanted. Now you can use index i to access elements of arrayTest as arrayTest[i] where i can vary from 0 to size-1 (inclusive).

查看更多
【Aperson】
3楼-- · 2020-07-22 10:08

Arrays don't have members. You have to use something like:

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

Better yet, if you must work with normal arrays instead of std::array, use a helper function. This also has the advantage of not breaking when you attempt it on a pointer instead of an array:

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

int size = array_size(arrayTest);
查看更多
做个烂人
4楼-- · 2020-07-22 10:23

arrayTest is not a class or struct but an array and it does not have member functions, in this case this will get your the size of the array:

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

although if your compiler supports C++11 than using std::array would be better:

#include <array>

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

as the document linked above shows you can also use range for loop to iterate over the elements of a std::array:

for( auto &elem : arrayTest )
{
   //Some operation here
}
查看更多
爷的心禁止访问
5楼-- · 2020-07-22 10:25

If you are stuck with arrays you can define your getArraySize function:

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

seen here: http://www.cplusplus.com/forum/general/33669/#msg181103

std::array remains the better solution.

查看更多
登录 后发表回答