当你只使用 return 时,函数返回什么类型;在 c++ 中

What type does a function return when you just use return; in c++

本文关键字:类型 什么 c++ 返回 函数 return 当你      更新时间:2023-10-16

我使用一个函数来返回我在数据文件中找到的obj。我想知道当没有相应的 obj 时它会返回什么类型的数据。这是我的代码。

BankAccount Find(string account_num , string password )
{
FILE_IN.seekg(0 , ios::beg);
int check = 0;
string temp1;
string temp2;
string temp3;
while(!FILE_IN.eof())
{
getline(FILE_IN , temp1);
getline(FILE_IN , temp2);
getline(FILE_IN , temp3);
if(account_num.compare(temp1) == 0 && password.compare(temp2) == 0)
check = 1;
}
if(check == 1)
{
fstream file;
file.open(temp3 , ios::out);
string name;
string hist;
string bal;
getline(file , name);
getline(file , bal);
file.ignore(numeric_limits<streamsize>::max() , 'n');
getline(file , hist , 'H');
BankAccount account = BankAccount(atoi(account_num.c_str()) , atoi(bal.c_str()) , password , name );
account.Enter_History(hist);
return account;
}
else
{
return;
}
}

您的程序格式不正确,不应编译时没有错误。不允许在具有非 void 返回类型的函数中使用不带操作数/值的return语句,请参阅 [stmt.return]/2 中的 C++17 标准草案。

您的程序不起作用。仅当此函数的类型BankAccount时,才能返回变量。 考虑使用单独的函数来检查所有内容是否有效,这样您就不必像在代码中那样处理边缘情况,或者返回某种 null-bankAccount(我不建议这样做(。

一个std::pair可以为你工作。 这样做不是最佳做法,但使用std::pair<BankAccount, bool> retVal您可以使用retVal.second来存储一个布尔值,该布尔值指示您的程序是否已正确执行。

我个人会使用尝试捕获块。 喜欢这个:

//Do stuff with Acc
if(acc.good == false){
throw std::invalid_argument("invalidAccount");

然后在调用函数时使用 try-catch 块。这样您就可以中断功能。 最好的方法可能是重新设计你的代码,这样就不会发生这种情况。

IDE 当时工作不准确!该代码的格式不正确,就像@wallnut的答案一样!该函数必须具有与其声明中的类型类似的返回类型。