[英]Base Operand of -> has non-pointer type error when creating an array of classes
我想了解为什么基本操作数->
在与指针一起使用时在某些情况下有效,而在其他情况下无效。
我意识到我需要使用.
而不是->
当我收到此错误时。 我试图理解为什么.
当我将指针作为数组元素引用为p[i].somefunct()
时需要,当我将指针直接引用为(p+i)->somefunct()
->
需要 ->。
我编写了一个示例程序来说明这两种方法,并想知道是否有更多有经验的声音可以解释这种 C++ 行为。
我也有兴趣了解是否有更好的方法来创建、访问和销毁指向存储在堆上的 class 的指针数组。
#include <iostream>
using namespace std;
class KClass {
public:
int x;
KClass(){};
~KClass(){};
int getx(){ return x; }
void setx(int data){ x = data; return; }
};
int main()
{
//use the heap to create an array of classes
KClass *pk = new KClass[3]; //array of 3 pointers
KClass *pk1 = new KClass[3]; //array of 3 pointers
//do something
for (int i = 0; i < 3; i++){
(pk+i)->setx(i);
cout << "(pk+" << i << ")->getx(): " << (pk+i)->getx() << endl;
}
cout << endl;
for (int i=0;i<3;i++){
//does not compile: pk1[i]->setx(i);
//why is different syntax required when I access pk1 as an element of an array?
pk1[i].setx(i);
cout << "pk1[" << i << "].getx(): " << pk1[i].getx() << endl;
}
delete [] pk;
delete [] pk1;
pk = nullptr;
pk1 = nullptr;
getchar();
return 0;
}
区别很简单。 p[i]
与*(p + i)
完全相同。 完全一样,以至于i[p]
是一种有效的(尽管非常令人困惑)编写数组订阅的形式。
因此,当您使用p[i]
表单时,您已经取消引用结果,因此您可以通过.
会员访问。
如果您在没有取消引用的情况下使用(p + i)
,则需要通过->
访问运算符访问成员,因为您正在处理指针。
只是一个 rehash - ->
只不过是方便快捷。 每当你写像a->x
这样的东西时,你总是可以把它写成(*a).x
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.