我想知道当一个整数被传递给一个接受指针的函数时,我将如何处理对函数的调用?在我的例子中,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 或在传入 NULL 时返回默认值来修正 hasPlayedInTeam
的定义:
//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
关于C++ - 采用指针但接收 int 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9953575/