C++中箭头运算符->的用法


C++中有不同类型的运算符,例如赋值运算符、算术运算符、关系运算符、逻辑运算符、按位运算符和许多其他运算符。
箭头运算符(arrow opertaor) -> ,也称为类成员访问运算符,是两个不同运算符的组合,即减号运算符 (-) 和大于运算符 (>)。它用于在指针变量的帮助下访问类、结构或联合成员的公共成员。

访问结构体

pointer -> class_member_name

下面是赋值语句和访问输出:

#include <iostream>
using namespace std;

struct Person
{
    char name[20];
    int age;
};

int main()
{
    // 创建结构体的指针对象
    struct Person *info = NULL;

    //动态分配内存
    info = (struct Person *)
        malloc(sizeof(struct Person));

    //箭头操作符用于赋值
    info->age = 17;

    //访问成员变量
    cout << "The age of the Person is = " << info->age;

    return 0;
}

程序的输出:

The age of Person is = 17

访问类

#include <iostream>
using namespace std;

// 创建一个类
class Student {
    private:
        // 声明私有成员
        int total_marks;
        float total_percentage;

    public:
        // 计算百分比
        void percentage(int total_marks)
        {
            this->total_marks=total_marks;
            total_percentage = (total_marks*100)/500;
        }
        //输出
        void print()
        {
            cout<<"Total percentage of the Student: "<<endl;
            cout<<total_percentage<<"%";
        }

};
 
int main()
{
   
    Student *s = new Student();
 
    // 访问类的成员函数
    s->percentage(387);
    s->print();
 
    return 0;
}

程序输出:

Total percentage of the student: 
77%

访问联合

#include <iostream>
using namespace std;

union Student
{
    string name;
    int roll;
};

int main()
{

    union Student *st = NULL;
    
    st = (union Student *)
        malloc(sizeof(union Student));

    // 给成员赋值
    st->roll = 21;

    // 打印值
    cout << "Roll: " << st->roll;
}

程序输出:

Roll: 21

关于箭头运算符和点运算符的区别,参考:
https://www.scaler.com/topics/arrow-operator-in-cpp/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhangjin1120

可靠的文章费时费力,希望支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值