C++ - 采用指针但接收 int 的方法

标签 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;
}

最佳答案

在你的通话中:

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/

相关文章:

c++ - 实现二进制搜索猜谜游戏

c++ - 检查文件是否存在于C++的某个目录中

c++ - 实现数据输入速记?

pointers - 在Go中返回时C struct为零

c++ - 指针的问题

c++ - 私有(private)析构函数

c++ - 使用 assimp 加载网格,并检测其中的边界和非流形边

c++ - 遇到中断语句时重新初始化指针变量

c - 如何从函数中取回指针的指针

c++ - 使用 std::vector<T*> 控制内存