[英]C++ Overloading with default parameters
i have a little question, how can i initialize default arguments in an function? 我有一个小问题,如何在函数中初始化默认参数?
#include <iostream>
#include <cmath>
using namespace std;
float area(float a, float b, float c);
float area(float a, float b=a, float c =a);
int main() {
cout << area(10) << endl;
return 0;
}
float area(float a, float b, float c){
return a*b*c
}
i am getting errors, how can i impelent correctly? 我遇到错误,如何正确执行?
You are going to have to use overloading instead of default parameters: 您将不得不使用重载而不是默认参数:
#include <iostream>
#include <cmath>
using namespace std;
float area(float a, float b, float c);
float area(float a);
int main() {
cout << area(10) << endl;
return 0;
}
float area(float a, float b, float c){
return a*b*c;
}
float area(float a){
return area(a,a,a);
}
If you want default value for b
and c
to be the value of a
then you should use overloading: 如果您想为默认值
b
和c
是价值a
,那么你应该使用重载:
float area(float a, float b, float c){
return a*b*c
}
float area(float a) {
return area(a, a, a);
}
C++ does not allow to use parameters as default arguments. C ++不允许将参数用作默认参数。 So this
所以这
float area(float a, float b=a, float c =a);
^^ ^^
is an Error. 是一个错误。
In C++ 在C ++中
you should prototype and implement the code for only one method including the optional parameters and the default values is the optional parameter is ommitted must be a constant and not an unknown value... 您应该仅对包括可选参数的一种方法进行原型设计并实现代码,并且默认值是省略可选参数的默认值必须是常量而不是未知值...
float area(float a, float b=0, float c=0);
int main() {
cout << area(10) << endl;
return 0;
}
float area(float a, float b=-1, float c =-1);){
if(b==-1 ||c==-1)
{
return a*a*a;
}else
{
return a*b*c;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.