函数 » 常见问题
我们将讨论一些初学者在使用函数时常犯的错误。
参数数量或类型不正确
在下面的 C++ 代码中,`sum` 函数期望两个整数参数,但函数调用传入了一个字符串和一个整数。
int sum(int a, int b){
return a + b;
}
int main(){
std::string num = "5";
std::cout << sum(num, 3);
}
编译器会报错。
error: no matching function for call to ‘sum(std::string&, int)’
为了解决这个错误,像这样在函数调用中传入两个整数:
int main(){
std::cout << sum(5, 3);
}
未返回值
考虑以下示例:`concatenate` 函数期望返回一个字符串,但该函数没有返回任何内容。
std::string concatenate(std::string a, std::string b)
{
a += b;
} // no return statement at the end
编译器会报错。
error: control reaches end of non-void function [-Werror=return-type]
为了解决这个错误,在函数中包含一个 `return` 语句来返回拼接后的字符串。
std::string concatenate(std::string a, std::string b) {
a += b;
return a;
}
提示
请注意,`main` 函数是此规则的一个例外。它不需要返回值。如果 `main` 函数没有返回值,编译器会假定该函数返回 `0`。
缺少声明
在以下代码中,`multiply` 函数在声明之前被调用。
int main(){
std::cout << multiply(3, 4); // error: use of undeclared identifier ‘multiply’
}
int multiply(int a, int b){
return a * b;
}