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
}
相关推荐
爱和冰阔落15 分钟前
C++模板进阶 非类型模板参数 模板的特化 分离编译的深入探索
c++·面试·编译原理·模板
charlie1145141916 小时前
精读C++20设计模式:行为型设计模式:中介者模式
c++·学习·设计模式·c++20·中介者模式
楼田莉子6 小时前
Qt开发学习——QtCreator深度介绍/程序运行/开发规范/对象树
开发语言·前端·c++·qt·学习
oioihoii7 小时前
超越 std::unique_ptr:探讨自定义删除器的真正力量
c++
Gohldg7 小时前
C++算法·贪心例题讲解
c++·数学·算法·贪心算法
天若有情6737 小时前
C++空值初始化利器:empty.h使用指南
开发语言·c++
远远远远子7 小时前
类与对象 --1
开发语言·c++·算法
无敌最俊朗@8 小时前
C/C++ 关键关键字面试指南 (const, static, volatile, explicit)
c语言·开发语言·c++·面试
利刃大大9 小时前
【高并发服务器】三、正则表达式的使用
服务器·c++·正则表达式·项目
小何好运暴富开心幸福10 小时前
C++之再谈类与对象
开发语言·c++·vscode