(->)箭头运算符和(.)点运算符,类指针 [英] (->) arrow operator and (.) dot operator , class pointer
问题描述
在c ++中,我们知道对于类的指针,我们使用(->)箭头运算符访问该类的成员,如下所示:
In c++ we know that for a pointer of class we use (->) arrow operator to access the members of that class like here:
#include <iostream>
using namespace std;
class myclass{
private:
int a,b;
public:
void setdata(int i,int j){
a=i;
b=j;
}
};
int main() {
myclass *p;
p = new myclass;
p->setdata(5,6);
return 0;
}
然后我创建一个"myclass"数组.
Then I create a array of "myclass".
p=new myclass[10];
但是,当我通过(->)箭头运算符访问myclass
成员时,出现以下错误
but then, when I go to access myclass
members through (->) arrow operator, I get following error
base operand of '->' has non-pointer type 'myclass'
但是当我通过(.)运算符访问类成员时,它可以工作.这些事情使我感到困惑.为什么要使用类数组,我必须使用(.)运算符.
but while I access class members through (.) operator it works. These things make me confused. Why for array of class I have to use (.) operator.
推荐答案
you should read about difference between pointers and reference that might help you understand your problem.
简而言之,区别是:
当声明myclass *p
时,它是一个指针,并且可以使用->
访问它的成员,因为p
指向内存位置.
In short, the difference is:
when you declare myclass *p
it's a pointer and you can access it's members with ->
, because p
points to memory location.
但是,只要您调用p=new myclass[10];
,p
就开始指向数组,当您调用p[n]
时,您将获得一个引用,必须使用.
访问哪些成员.
但是,如果使用p->member = smth
就像调用p[0].member = smth
一样,因为[]
中的数字是从p
到搜索下一个数组成员的位置的偏移量,例如(p + 5)->member = smth
为p[5].member = smth
But as soon as you call p=new myclass[10];
p
starts to point to array and when you call p[n]
you get a reference, which members must be accessed using .
.
But if you use p->member = smth
that would be the same as if you called p[0].member = smth
, because number in []
is an offset from p
to where search for the next array member, for example (p + 5)->member = smth
would be same as p[5].member = smth
这篇关于(->)箭头运算符和(.)点运算符,类指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!