如何使C++函数使用双精度参数或无参数执行

How to make a C++ function execute with a double parameter or no parameter

本文关键字:参数 执行 双精度 何使 C++ 函数      更新时间:2023-10-16

我有一些代码,我有 3 个重载函数。我希望其中一个接受双精度作为参数,或者在没有传递的参数时调用。其他人只接受一个 int,另一个接受一个字符,仅此而已。我该怎么做呢?

如果您希望在

用户进行没有参数的调用时执行函数,请为参数指定默认值:

void foo(double d = 0.0) {
    ...
}
void foo(int i) {
    ...
}
void foo(char c) {
    ...
}

当用户调用foo()时,将调用重载接收double。代码将像传递零一样执行。

检查此代码:

#include <iostream>
using namespace std;
void foo(double x=0.0) // give it a default value for it to be called with no arguments
{
    cout<<"foo(double) is being called"<<endl;
}
void foo(int x)
{
    cout<<"foo(int) is being called"<<endl;
}
void foo(char x)
{
    cout<<"foo(char) is being called"<<endl;
}
int main() 
{
    foo();
    foo(3.5);
    foo(10);
    foo('c');
    return 0;
}

输出:
foo(双)被调用
foo(双)被调用
foo(int) 被调用
foo(char) 被调用