数组大小成员函数编译错误 [英] Array Size Member Function Compile Error

查看:167
本文介绍了数组大小成员函数编译错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

本$ C $工作c:

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

编译器错误:

错误:请求成员的大小'在'myArray的,这是无级式INT [10]|

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.

推荐答案

数组类型不是类类型,并且没有成员函数。因此,一个数组没有名为的成员函数尺寸。然而,由于阵列具有编译时固定的大小,你的知道的大小为 10

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;

您可以,但是,使用的std ::阵列相反,它封装了一个数组类型的对象为您和确实提供了一个尺寸成员函数:

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;

这篇关于数组大小成员函数编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆