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
}
相关推荐
在路上看风景1 小时前
19. 成员初始化列表和初始化对象
c++
zmzb01031 小时前
C++课后习题训练记录Day98
开发语言·c++
念风零壹2 小时前
C++ 内存避坑指南:如何用移动语义和智能指针解决“深拷贝”与“内存泄漏”
c++
孞㐑¥3 小时前
算法——BFS
开发语言·c++·经验分享·笔记·算法
MZ_ZXD0014 小时前
springboot旅游信息管理系统-计算机毕业设计源码21675
java·c++·vue.js·spring boot·python·django·php
A星空1235 小时前
一、Linux嵌入式的I2C驱动开发
linux·c++·驱动开发·i2c
凡人叶枫6 小时前
C++中智能指针详解(Linux实战版)| 彻底解决内存泄漏,新手也能吃透
java·linux·c语言·开发语言·c++·嵌入式开发
会叫的恐龙6 小时前
C++ 核心知识点汇总(第六日)(字符串)
c++·算法·字符串
小糯米6016 小时前
C++顺序表和vector
开发语言·c++·算法
独望漫天星辰6 小时前
C++ 多态深度解析:从语法规则到底层实现(附实战验证代码)
开发语言·c++