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
}
相关推荐
Brilliantwxx21 小时前
【算法题】 面试级别的二叉树题目OJ复习(下)
数据结构·c++·算法·leetcode·面试·哈希算法·推荐算法
阿方.91821 小时前
C++ string 超全精讲 | 从零使用、底层原理、手搓简易string、高频考点、易错点、面试手撕
开发语言·c++·字符串·string·知识分享
fish_xk1 天前
c++11(二)
java·前端·c++
张小姐的猫1 天前
【Linux】多线程实战 —— 日志类 | 策略模式
linux·运维·服务器·c++·bash·策略模式
闻缺陷则喜何志丹1 天前
P8134 [ICPC 2020 WF] Opportunity Cost|普及+
c++·算法·洛谷
不会C语言的男孩1 天前
C++ Primer Plus 第2章:开始学习C++
开发语言·c++
c238561 天前
MySrting的模拟实现
开发语言·c++·算法
Rabitebla1 天前
C++ 继承详解(下):默认成员函数、虚继承底层与设计取舍
c语言·开发语言·数据结构·c++·算法·leetcode
wljy11 天前
二、进制状态转换
linux·运维·服务器·c语言·c++
云泽8081 天前
笔试算法 -位运算篇(二):从唯一字符到消失数字
c++·算法·位运算