C – 接收指针但接收int的方法
发布时间:2020-12-16 10:21:40 所属栏目:百科 来源:网络整理
导读:我想知道当一个整数传递给接受指针的函数时,我将如何处理对函数的调用?在我的情况下,hasPlayedInTeam()接受指向Team的指针,但是,收到了一个int.这会导致Q_ASSERT挂起. 另外,我的问题也称为空指针?我的教授在讲座中多次使用过这个术语,但我不确定他指的是什
我想知道当一个整数传递给接受指针的函数时,我将如何处理对函数的调用?在我的情况下,hasPlayedInTeam()接受指向Team的指针,但是,收到了一个int.这会导致Q_ASSERT挂起.
另外,我的问题也称为空指针?我的教授在讲座中多次使用过这个术语,但我不确定他指的是什么. //main.cpp Person p1("Jack",22,"UCLA"); Q_ASSERT(p1.hasPlayedInTeam(0) == false); //person.cpp bool Person::hasPlayedInTeam(Team *pTeam) { bool temp = false; foreach (Team* team,teamList) { if (team->getName() == pTeam->getName() { temp = true; } } return temp; } 解决方法
在你的电话中:
p1.hasPlayedInTeam(0) 整数文字0转换为NULL指针.所以,你实际上并没有“接收”一个整数;你传递一个整数,编译器可以自动将它转换为空指针(给定NULL的定义). 我认为您可以通过断言其参数不是NULL来修复hasPlayedInTeam的定义,或者在传入NULL时返回默认值: //person.cpp bool Person::hasPlayedInTeam(Team *pTeam) { assert(pTeam!=NULL); //-- in this case,your program will assert and halt 要么: //person.cpp bool Person::hasPlayedInTeam(Team *pTeam) { if (pTeam == NULL) return false; //-- in this case,your program will not assert and continue with a sensible (it actually depends on how you define "sensible") return value (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |