->和 . 都是对结构体进行访问的时候使用,但是有区别。
->是用指针访问结构体数据的时候使用,例如如下代码块中:
ShowAddress(people *a )函数,传进来的形参是一个指向结构体a的指针,因此想通过该指针去访问里面的数据的时候就应该用a->name,a->age,a->address.
ShowName(people *a)函数,传进来的形参是结构体a,因此访问结构体a里面的数据的时候,直接用a.name,a.age,a.address
//->和.的使用
#include <iostream>
#include <string>
using namespace std;
struct people
{
string name;
int age;
string address;
};
void ShowAddress(people* a);
void ShowName(people a);
int main()
{
people a;
string Name;
int Age;
string Address;
cout << "请输入名称 :" << endl;
cin >> Name;
a.name = Name;
cout << "请输入年龄:" << endl;
cin >> Age;
a.age = Age;
cout << "请输入地址:" << endl;
cin >> Address;
a.address = Address;
cout << "您输入的地址是:" << endl;
ShowAddress(&a);
cout << "您输入的名字是:" << endl;
ShowName(a);
return 0;
}
//函数的定义
void ShowAddress(people *a)
{
cout << "地址是:" << a->address << endl;
}
void ShowName(people a)
{
cout << "名字是:" << a.name << endl;
}
结果: