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
}
相关推荐
hetao17338378 小时前
2025-12-12~14 hetao1733837的刷题笔记
数据结构·c++·笔记·算法
椰子今天很可爱8 小时前
五种I/O模型与多路转接
linux·c语言·c++
程序员zgh8 小时前
C++ 互斥锁、读写锁、原子操作、条件变量
c语言·开发语言·jvm·c++
獭.獭.10 小时前
C++ -- STL【unordered_set和unordered_map的使用】
c++·stl·unordered_map·unordered_set
star _chen11 小时前
C++ std::move()详解:从小白到高手
开发语言·c++
福尔摩斯张11 小时前
C++核心特性精讲:从C语言痛点出发,掌握现代C++编程精髓(超详细)
java·linux·c语言·数据结构·c++·驱动开发·算法
charlie11451419112 小时前
如何快速在 VS2026 上使用 C++ 模块 — 完整上手指南
开发语言·c++·笔记·学习·现代c++
报错小能手13 小时前
STL_unordered_map
开发语言·c++·哈希算法
历程里程碑13 小时前
C++ 9 stack_queue:数据结构的核心奥秘
java·开发语言·数据结构·c++·windows·笔记·算法
仰泳的熊猫13 小时前
1108 Finding Average
数据结构·c++·算法·pat考试