Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

c++ - Array Size Member Function Compile Error

Working with this code:

int myArray[10];
    for(int i = 0; i < myArray.size(); i++)
        cout << myArray[i] << endl;

Compiler error:

error: request for member 'size' in 'myArray', which is of non-class type 'int [10]'|

I must be missing something obvious but I don't see it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Array types are not class types and don't have member functions. So an array doesn't have a member function called size. However, since arrays have compile-time fixed sizes, you know the size is 10:

for(int i = 0; i < 10; i++)
    cout << myArray[i] << endl;

Of course, it's best to avoid magic numbers and put the size in a named constant somewhere. Alternatively, there is a standard library function for determining the length of an array type object:

for(int i = 0; i < std::extent(myArray); i++)
    cout << myArray[i] << endl;

You may, however, use std::array instead, which encapsulates an array type object for you and does provide a size member function:

std::array<int, 10> myArray;
for(int i = 0; i < myArray.size(); i++)
    cout << myArray[i] << endl;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...