Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 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 Reply

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...