简体   繁体   中英

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:

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. So this

float area(float a, float b=a, float c =a);
                           ^^          ^^

is an Error.

In 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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM