c++ - 可以函数返回 0 作为引用

标签 c++

I have this snippet of the code

Account& Company::findAccount(int id){
        for(list<Account>::const_iterator i = listOfAccounts.begin(); i != listOfAccounts.end(); ++i){
            if(i->nID == id){
                return *i;
            }
        }
        return 0;
    }

如果我没有找到合适的帐户,这是返回 0 的正确方法吗? 因为我收到一个错误:

no match for 'operator!' in '!((Company*)this)->Company::findAccount(id)'

我是这样使用的:

if(!(findAccount(id))){
            throw "hey";
          }

提前致谢

最佳答案

没有空引用这样的东西。标准说:

A reference shall be initialized to refer to a valid object or function. [ Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer, which causes undefined behavior.

关于c++ - 可以函数返回 0 作为引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3060545/

相关文章:

c++ - 在 Ubuntu 上构建 QT 5

c++ - C++将time_t读入不同的时区,然后提取年/月…纳秒

c++ - 出于不同目的重复读取由空格(或其他分隔符)分隔的 double 列表

c++ - 寻找第 3 方 Qt 甘特图组件

c++ - 在 typedef 结构中声明一个数组

c++ - 解释这个素数程序 [C]

c++ - boost::multiprecision::cpp_int 是 POD 吗?

c++ - 读写文件到数组

c++ - QGraphicsScene、QTextEdit 和失去焦点

java - JNI CallObjectMethod 搞砸了堆栈框架?