(我是 C++ 的初学者。但我熟悉其他一些编程语言,特别是 Java。)
谁能帮我找出这个 C++ 代码中的缺陷?
string & getFullName(string name, bool male){
string fullName = name;
if (male) {
fullName = string(” Mr. ”) + fullName;
return fullName;
}
}
(我是 C++ 的初学者。但我熟悉其他一些编程语言,特别是 Java。)
谁能帮我找出这个 C++ 代码中的缺陷?
string & getFullName(string name, bool male){
string fullName = name;
if (male) {
fullName = string(” Mr. ”) + fullName;
return fullName;
}
}
您正在返回对局部变量的引用。理想情况下,这意味着一旦函数 getFullName 返回,fullName 就会消失,并且如果您尝试为其分配类似
string myName = getFullName("Adam",true);
myName
会是垃圾。
不要返回对本地的引用并删除单个左卷曲:
void makeFullName(string &name, bool male){
if (male) /* remove the curly */
name = string(“Mr. ”) + name;
}
The scope of the fullname is limited to this function only, hence once this function ends or goes out of scope, fullname is removed from the stack. Therefore when you return the reference of fullname, you return the address of flushed up memory hence you will get garbage value. The other problem is when the condition of male is false, you are not returning anything.
你可能想要更像这样的东西:
std::string getFullName(string const &name, bool male) {
std::string ret = "Mr. ";
if (male)
return ret+name;
return name;
}
如果您选择,另一种可能性也可以更轻松地为女性姓名添加标题:
std::string getFullName(string const &name, bool male) {
static const std::string titles[] = {std::string(""), std::string("Mr. ")};
return titles[male] + name;
}
如果您确实想要在女性姓名中添加标题,只需将其插入上面的空字符串即可。