[C++] 对象指针使用方法

对象指针:指向类对象的指针

类指针指向类变量(对象)的地址

 

对象指针定义格式:

类类型 *变量名;

 

举例:

#include <iostream>

using namespace std;

class Student {
private:
    int age;
public:
    void setAge(int n) {
        this->age = n;
    }

    int getAge() {
        return this->age;
    }
};

int main(void) {
    Student stu;
    Student *pStu = &stu;

    // 对象用.访问公有成员
    stu.setAge(12);
    // 对象指针用->访问共有成员
    cout << pStu->getAge() << endl;

    return 0;
}

 

posted @ 2019-12-09 20:49  LeeAaron  阅读(1171)  评论(0编辑  收藏  举报