->
,也称为类成员访问运算符,是两个不同运算符的组合,即减号运算符 (-) 和大于运算符 (>)。它用于在指针变量的帮助下访问类、结构或联合成员的公共成员。
pointer -> class_member_name
下面是赋值语句和访问输出:
#include
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
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: "<percentage(387);
s->print();
return 0;
}
程序输出:
Total percentage of the student:
77%
#include
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/