结构体引用中点(.)与箭头(->)的区别:
(推荐使用-> 对于结构体类型的变量的成员的访问,无论数据类型如何都可以使用箭头访问!!)
项目场景:
提示:通讯录管理系统中的添加联系人函数
问题描述:
提示:这里描述项目中遇到的问题:
例如:数据传输过程中数据不时出现丢失的情况,偶尔会丢失一部分数据
APP 中接收数据代码:
void add_contacts(Mycontacts* mycontacts)
{
//输出当前通讯录中的人数
cout << "当前通讯录中的人数:" << mycontacts.num_contacts << endl;
int index = mycontacts.num_contacts;
string name;
cout << "输入联系人的姓名:" << endl;
cin >> name;
mycontacts.Contacts[index].name = name;
string sex;
cout << "输入联系人的性别:" << endl;
cin >> sex;
mycontacts.contacts[index].sex = sex;
int age;
cout << "输入联系人的年龄:" << endl;
cin >> age;
mycontacts,Contacts[index].age = age;
string number;
cout << "输入联系人的联系电话:" << endl;
cin >> number;
mycontacts.Contacts[index].number = number;
string adress;
cout << "输入联系人的家庭地址:" << endl;
cin >> adress;
mycontacts.Contacts[index].adress = adress;
mycontacts.num_contacts += 1;
}
# 原因分析:
int main(){
struct Mycontacts mycontacts;
mycontacts.num_contacts = 0;
add_contacts(&mycontacts);
....}
主函数中首先定义了一个结构体数组,传入函数时候只能采用地址传递
箭头(->):左边的操作数必须为指针;
点号(.):左边的操作数必须为实体。
所以访问结构体成员的时候必须使用箭头操作。
# 解决方案:
//输出当前通讯录中的人数
cout << "当前通讯录中的人数:" << mycontacts->num_contacts << endl;
int index = mycontacts->num_contacts;
string name;
cout << "输入联系人的姓名:" << endl;
cin >> name;
mycontacts->Contacts[index].name = name;
string sex;
cout << "输入联系人的性别:" << endl;
cin >> sex;
mycontacts->Contacts[index].sex = sex;
int age;
cout << "输入联系人的年龄:" << endl;
cin >> age;
mycontacts->Contacts[index].age = age;
string number;
cout << "输入联系人的联系电话:" << endl;
cin >> number;
mycontacts->Contacts[index].number = number;
string adress;
cout << "输入联系人的家庭地址:" << endl;
cin >> adress;
mycontacts->Contacts[index].adress = adress;
mycontacts->num_contacts += 1;