C++中的符号->

在C++中,符号"->"用于访问指向对象的指针的成员。它也被称为箭头运算符或取消引用运算符。

使用"->"符号的基本语法是:

对象指针->成员名称

这里,object_pointer是指向对象的指针,member_name是属于该对象的成员变量或函数。

示例:

通过指针访问成员变量:

cpp 复制代码
#include <iostream>
using namespace std;

class MyClass {
public:
    int myVar;
};

int main() {
    MyClass* objPtr = new MyClass(); // Creates an object of MyClass and assigns it to objPtr
    objPtr->myVar = 42; // Sets the value of myVar in the object pointed by objPtr to 42
    cout << objPtr->myVar << endl; // Outputs: 42
    delete objPtr; // Frees the memory allocated for the object pointed by objPtr
}

注意:"MyClass*objPtr=new MyClass();"和"MyClass*objPtr=new MyClass[()]"之间没有区别。这两个语句都是等效的,并使用"new"关键字创建指向类MyClass实例的指针。唯一的区别是类型名和变量名之间的间距,这会影响代码的可读性。有些程序员更喜欢在类型名称后面有一个空格,而另一些则不喜欢。然而,这纯粹是个人偏好的问题,不会影响代码的功能或正确性。

通过指针调用成员函数:

cpp 复制代码
#include <iostream>
using namespace std;

class MyClass {
public:
    void printHello() {
        cout << "Hello!" << endl;
    }
};

int main() {
    MyClass* objPtr = new MyClass(); // Creates an object of MyClass and assigns it to objPtr
    objPtr->printHello(); // Calls the printHello() member function of the object pointed by objPtr and prints "Hello!" to the console
    delete objPtr; // Frees the memory allocated for the object pointed by objPtr
}
相关推荐
金色熊族2 分钟前
装饰器模式(c++版)
开发语言·c++·设计模式·装饰器模式
Dream it possible!24 分钟前
LeetCode 面试经典 150_链表_旋转链表(64_61_C++_中等)
c++·leetcode·链表·面试
CS创新实验室3 小时前
典型算法题解:长度最小的子数组
数据结构·c++·算法·考研408
我有一些感想……3 小时前
浅谈 BSGS(Baby-Step Giant-Step 大步小步)算法
c++·算法·数论·离散对数·bsgs
j_xxx404_3 小时前
C++ STL:string类(3)|operations|string类模拟实现|附源码
开发语言·c++
Elias不吃糖5 小时前
Linux 环境适应 Day 1 全面笔记
linux·c++·笔记
无限进步_6 小时前
C语言字符串连接实现详解:掌握自定义strcat函数
c语言·开发语言·c++·后端·算法·visual studio
oscar9996 小时前
CSP-J教程——第一阶段——第二课:变量与数据类型
c++·数据类型·csp-j
qwepoilkjasd6 小时前
RapidJSON 完整学习指南
c++
一朵筋斗云6 小时前
c++
c++