(->)箭头运算符和(.)点运算符,类指针 [英] (->) arrow operator and (.) dot operator , class pointer

查看:230
本文介绍了(->)箭头运算符和(.)点运算符,类指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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 = smthp[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屋!

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