Table of contents
There are different types of operators in C++ such as assignment operators, arithmetic operators, relational operators, logical operators, bitwise operators and many others. The arrow operator
,
->
also known as the class member access operator, is a combination of two different operators, the minus operator (-) and the greater than operator (>). It is used to access public members of a class, structure or union members with the help of pointer variables.
access structure
pointer -> class_member_name
Here is the assignment statement and access output:
#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;
}
Program output:
The age of Person is = 17
access class
#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;
}
Program output:
Total percentage of the student:
77%
visit union
#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;
}
Program output:
Roll: 21
Regarding the difference between arrow operators and dot operators , please refer to:
https://www.scaler.com/topics/arrow-operator-in-cpp/