C++ - 获取指针但接收int的方法

Jon*_*Jon 3 c++ pointers

我想知道当一个整数传递给接受指针的函数时,我将如何处理对函数的调用?在我的情况下,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;
}
Run Code Online (Sandbox Code Playgroud)

ser*_*gio 7

在你的电话中:

p1.hasPlayedInTeam(0)
Run Code Online (Sandbox Code Playgroud)

整数文字0转换为NULL指针.所以,你实际上并没有"接收"一个整数; 你传递一个整数,编译器可以自动将它转换为空指针(给定NULL的定义).

我认为您可以hasPlayedInTeam通过声明其参数不是NULL 来修复定义,或者在传入NULL时返回默认值:

//person.cpp
bool Person::hasPlayedInTeam(Team *pTeam) {
    assert(pTeam!=NULL); //-- in this case, your program will assert and halt
Run Code Online (Sandbox Code Playgroud)

要么:

//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
Run Code Online (Sandbox Code Playgroud)