在这种情况下,过载不起作用

Overload not working in this instance?

本文关键字:不起作用 这种情况下      更新时间:2023-10-16
    // How to write a function and use.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;

double add(double x, double y)
{
    return x+ y;
}
double add(double a, double b, double c)
{
    return a + b + c;
}

    int main()
    {
        auto a = add(3, 4);                              // calling the funciton
        cout << "3 + 4 is " << a;                       // printing a out
        double b = add(1.2, 3.4);                       // calling the funciton
        cout << endl;
        cout << "1.2 + 3.4 is " << b;                   // printing a out
        cout << endl;
        double c = add(1.2 + 2.2 + 3.3);
        cout << "1.1 + 2.2 + 3.3 is" << c;
        return 0;
    }

大家好,我正在尝试使用"添加"两次进行重载。 由于某种原因,我第二次使用 add 时,它没有被识别为重载。 我收到一个错误,没有重载函数需要 1 个参数。 第一次添加工作正常,但第二次添加不能。

有人可以看看解释我做错了什么吗? 我看不出我的代码有什么问题? 我正在使用Visual Studio C++。

谢谢。

问题就在这里:

double c = add(1.2 + 2.2 + 3.3);

1.2 + 2.2 + 3.3 是类型 double 的表达式。

但是,您尚未指定具有单个参数的add版本,double将转换为该参数,因此编译器会发出错误。

你是说double c = add(1.2, 2.2, 3.3);吗?

    double c = add(1.2 + 2.2 + 3.3);

你在上面做什么?本质上,您正在将单个参数传递给add(1.2、2.2 和 3.3 求和的结果)。您是否使用单个参数定义了add?不,因此错误。

double c = add(1.2 + 2.2 + 3.3);应替换为double c = add(1.2, 2.2, 3.3);,因为第一个表达式的参数将是 1.2、2.2、3.3 的加法,并将其转换为单个参数。

没有一个版本的add需要双精度:

double c = add(1.2 + 2.2 + 3.3); // they are summed ans passed as one parameter.

然后重载它:

double add(double a)
{
    return a;
}

但是,函数中没有逻辑可以将您声明的任何值相加。