c++指向对象的双重指针不需要解引用用数组下标访问所指对象属性和方法的问题

// write a point array in a file
#include <iostream>
#include <string>
using namespace std;

class person
{
public:
  string name;
  int age;
  string address;
  string phone;
  string email;

public:
  person()
  {
    name = "Tony";
    age = 0;
    address = "123";
    phone = "123";
    email = "123";
    cout << "Address of the current object "<<this << endl;
  }
};
int main()
{
  person p1;
  //person p2;
  person *q[2];
  person **q1;

  q[0] = &p1;
  //q[1] = &p2;
  q1 = q;
  //Address of the current object
  cout << "p1 address " << &p1 << endl;
  cout << "q[0] value " << q[0] << endl;
  cout << "*q1 value " << *q1 << endl;
  cout << "q1[0] value " << q1[0]<< endl;
  
  //可以深入了解对象调用方法属性的机制:只要有了当前对象的地址,就可以调用对象的方法属性
  //因为对象创建的时候会有this指针默认创建,所以可以直接调用对象的方法属性
  //以上的表示方法都可以存入对象的地址,所以可以直接用q1[0]调用对象的方法属性
  cout << "------------------------------" << endl; 
  // cout << *q1->name << endl;//这个不能解析是因为*q1是具体的值不是指针了
  cout <<  q[0]->name << endl;
  cout << q1[0]->name << endl;
  cout << p1.name << endl;
  //而因为数组的本质就是指针,方括号等于解引用,看下例子
  char b = 'c';
  char *a = &b;
  cout << "*a is " << *a << endl;
  cout <<"a[0] is "<< a[0] << endl;
  
  cout << "------------------------------" << endl;  
  cout << "q address " << q << endl;
  cout << "q1 value " << q1 << endl;


}

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值