错误是什么意思"expression must have class type"?
What does "expression must have class type" error mean?
#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
可以从0
到size-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仍然是更好的解决方案。
相关文章:
- unordered_set .find 方法无法编译的 C++ "expression must have class type"错误
- 调用 list.size() 方法给出错误"expression must have class type"
- 为什么我会收到"Expression must have a class type"错误?(C++)
- 让编译器告诉哪些方法不具体,而不是错误'invalid new-expression of abstract class type'
- 仅当链接函数 C++ 时,才会发生"Expression must have class type error"
- 错误 - "expression must have a class type" - c++
- "Expression must have class type"错误
- C++模板"class type"错误
- 使用带有对象的数组调用类中的方法,错误"non-class type",c++
- "Allocating an object of abstract class type"错误,尽管所有函数都有实现
- deque.push_front() 给出错误"expression must have class type"
- "does not have a class type"错误
- C++:离奇发生的"Request for member X of Y which is of non-class type Z"
- 如何处理"class type redefinition"
- 这个错误是什么意思" expression must have pointer-to-class type"?
- 错误是什么意思"expression must have class type"?
- 夏亚"Expression Must Have A Class Type"
- 链表函数 C++ "which is of non-class type 'int'" ?
- shared_ptr : "call of an object of a class type without appropriate operator() or conversion functio
- "Expression must have class type" 错误,尝试调用类函数