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
}
相关推荐
超爱笑嘻嘻27 分钟前
shared_ptr八股收集 C++
c++
我想进大厂1 小时前
图论---朴素Prim(稠密图)
数据结构·c++·算法·图论
我想进大厂1 小时前
图论---Bellman-Ford算法
数据结构·c++·算法·图论
光而不耀@lgy1 小时前
C++初登门槛
linux·开发语言·网络·c++·后端
啊丢_1 小时前
C++——Lambda表达式
开发语言·c++
Wendy_robot2 小时前
【滑动窗口+哈希表/数组记录】Leetcode 438. 找到字符串中所有字母异位词
c++·算法·leetcode
转基因3 小时前
Codeforces Round 1020 (Div. 3)(题解ABCDEF)
数据结构·c++·算法
whoarethenext3 小时前
c++的jsoncpp使用
开发语言·c++·jsoncpp
我想进大厂4 小时前
图论---Kruskal(稀疏图)
数据结构·c++·算法·图论
_w_z_j_5 小时前
C++----模拟实现string
开发语言·c++