// 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 ++。
谢谢。
答案 0 :(得分:10)
问题在于:
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);
吗?
答案 1 :(得分:2)
double c = add(1.2 + 2.2 + 3.3);
你在做什么?基本上你是将一个参数传递给add
(总结1.2,2.2和3.3的结果)。你用一个参数定义了add
吗?不,因此错误。
答案 2 :(得分:2)
double c = add(1.2, 2.2, 3.3);
应替换为exports.inject = function (app) {
app.controller('sevenIntAFFECTinit.Controller', exports.controller);
exports.controller.$inject = ['$scope', '$state', '$stateParams', 'jsonPartialService', '$log', '$rootScope'];
return exports.controller;
};
exports.controller = function sevenIntAFFECTinitCtrl($scope, $state, $stateParams, jsonPartialService, $log, $rootScope) {
// Do the json in here. Jokes
$rootScope.slides = [];
jsonPartialService
.getJSON('part-1/7-INT-QUIZ-AFFECT')
.then(function (response) {
$scope.prevState = response.prev_state;
$scope.nextState = response.next_state;
$scope.quizTitle = response.quiz_title;
buildData(response);
});
function buildData(resp) {
for (var item in resp.quiz_slides) {
if (resp.quiz_slides) {
$rootScope.slides.push(resp.quiz_slides[item]);
}
}
$log.debug('after the slides have been pushed in init -->', $rootScope.slides);
$state.go('7-INT-QUIZ-AFFECT.detail', $stateParams, {reload: true, inherit: false});
}
};
,因为第一个表达式的参数将是1.2,2.2,3.3的加法,并使其成为单个参数。
答案 3 :(得分:0)
add
没有版本需要一两倍:
double c = add(1.2 + 2.2 + 3.3); // they are summed ans passed as one parameter.
然后重载它:
double add(double a)
{
return a;
}
但是函数中没有任何逻辑可以将任何用一个声明它的值求和。