夜听风雨声
夜听风雨声

Reputation: 27

A problem of function declaration and function definition in Visual Studio

I am a beginner in C++ and I got some problems. I'll appreciate it a lot if anyone helps me. My English is not very good. I write the code in the Visual Studio. When I use the overloaded function and default parameter at the same time, it' OK as follows:

    double max(double a, double b, double c, double d = 3.1415926)
    {
        cout << "pi: " << d << endl;
        if (a > b && a > c)
            return a;
        else if (b > a && b > c)
            return b;
        else
            return c;
    }
    

    int max(int a, int b, int c, int d = 20)
    {
        cout << "d: " << d << endl;
        if (a > b && a > c)
            return a;
        else if (b > a && b > c)
            return b;
        else
            return c;
     }

    int main()
    {
        int x = 10, y = 6, z = 23;
        double m = 1.2, n = 4.2, k = 3.1;

        cout <<"max value in x, y, z: "<< max(x, y, z) << endl;
        cout <<"max value in m, n, k: "<< max(m, n, k) << endl;
        return 0;
    }

However, if I declare the function at first and then define it at last, an error occurred as follows:

int max(int a, int b, int c, int d = 20);
double max(double a, double b, double c, double d = 3.1415926);

int main()
{
    int x = 10, y = 6, z = 23;
    double m = 1.2, n = 4.2, k = 3.1;
    cout <<"max value in x, y, z: "<< max(x, y, z) << endl;
    cout <<"max value in m, n, k: "<< max(m, n, k) << endl;

    return 0;
}

double max(double a, double b, double c, double d = 3.1415926)
{
    cout << "pi: " << d << endl;
    if (a > b && a > c)
        return a;
    else if (b > a && b > c)
        return b;
    else
        return c;
}


int max(int a, int b, int c, int d = 20)
{
    cout << "d: " << d << endl;
    if (a > b && a > c)
        return a;
    else if (b > a && b > c)
        return b;
    else
        return c;
}

The Visual Studio shows Severity Code Description File Line Error C2572 'max': redefinition of default argument: parameter 1

Thank you very much.

Upvotes: 0

Views: 160

Answers (1)

Jorenar
Jorenar

Reputation: 2884

Default value you specify only once - in function prototype:

int max(int a, int b, int c, int d = 20);

int main()
{
    // code...
}

int max(int a, int b, int c, int d)
{
    // code...
}

The same with double version

Upvotes: 2

Related Questions