【发布时间】:2021-02-02 18:00:39
【问题描述】:
我想了解为什么基操作数 -> 在与指针一起使用时在某些情况下有效,而在其他情况下无效。
我意识到当我收到此错误时,我需要使用 . 而不是 ->。我试图理解为什么当我将指针作为数组元素引用为p[i].somefunct() 时需要.,而当我将指针直接引用为(p+i)->somefunct() 时需要->。
我编写了一个示例程序来说明这两种方法,想知道是否有更有经验的人可以解释这种 C++ 行为。
我也有兴趣了解是否有更好的方法来创建、访问和销毁指向存储在堆上的类的指针数组。
#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;
}
【问题讨论】: