结构体引用中点(.)与箭头(->)的区别

本文介绍了在C++中,结构体成员访问时使用点号(.)和箭头(->)的区别。在项目场景中,特别是在通讯录管理系统的添加联系人函数中,由于数据传递采用指针方式,必须使用箭头操作符来访问结构体成员。文章通过错误示例展示了数据丢失问题,并提供了修正方案,强调了在指针操作结构体时,必须使用->来访问成员,以避免混淆和潜在的运行时错误。
摘要由CSDN通过智能技术生成

结构体引用中点(.)与箭头(->)的区别:
(推荐使用-> 对于结构体类型的变量的成员的访问,无论数据类型如何都可以使用箭头访问!!)

项目场景:

提示:通讯录管理系统中的添加联系人函数

问题描述:

提示:这里描述项目中遇到的问题:
例如:数据传输过程中数据不时出现丢失的情况,偶尔会丢失一部分数据
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;





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值