我目前正在研究一些代碼,這些代碼將在Person類型的矢量(我已在代碼中定義並將在需要時顯示)中進行搜索。如果發現該人,則返回他們的姓名。這是目前正在工作,但如果它沒有找到該人,它應該返回一個空指針。問題是,我無法弄清楚如何讓它返回一個空指針!它只是保持每次崩潰的程序。如何返回函數中的空指針C++
代碼:
Person* lookForName(vector<Person*> names, string input)
{
string searchName = input;
string foundName;
for (int i = 0; i < names.size(); i++) {
Person* p = names[i];
if (p->getName() == input) {
p->getName();
return p; //This works fine. No problems here
break;
} else {
//Not working Person* p = NULL; <---Here is where the error is happening
return p;
}
}
}
只是返回 '0'(零)。這是C++中空指針的表示形式。 –
'nullptr'會更好,但嚴重的是,使用'std :: find_if',最好是不帶指針的'std :: vector'。 –
chris
哦,你也沒有初始化P,所以在任何情況下它都會有一個值!= 0.請記住,C++不會自動初始化它的變量。 –