在这种情况下,过载不起作用
Overload not working in this instance?
// 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;
}
但是,函数中没有逻辑可以将您声明的任何值相加。
相关文章:
- G++ C++17 类模板参数推导在非常特殊的情况下不起作用
- 为什么在这种情况下,前向声明不起作用?
- 为什么 std::void_t 在这种情况下不起作用
- 为什么在这种情况下 boost::recursive_wrapper 不起作用
- 为什么在这种情况下创建临时实例不起作用?
- 为什么SFINAE在这种情况下不起作用?
- 为什么在这种情况下转发引用不起作用?
- 在这种情况下,过载不起作用
- 为什么模板论点不能在这种情况下推导
- 请帮助我理解为什么SFINAE在这种情况下不起作用
- 为什么#ifndef在这种情况下不起作用
- 为什么c_str在这种打开(文件名)的情况下不起作用
- 在这种情况下__declspec( align( # ) ) 不起作用
- 为什么cvPutText在这种情况下不起作用?
- 在这种情况下,最小和最大根本不起作用?
- 内联扩展可能不起作用的情况
- 为什么贪婪的方法在这种情况下不起作用?
- 为什么 std::function<boost::any ()> 在这种情况下不起作用?
- 为什么在这种情况下"自动"不起作用?
- 为什么多态性在这种情况下不起作用