如何使C++函数使用双精度参数或无参数执行
How to make a C++ function execute with a double parameter or no parameter
我有一些代码,我有 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) 被调用
相关文章:
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- 如何将带有参数的愚蠢函数添加到愚蠢的执行器中?
- 如何将成员函数作为参数传递并在派生对象上执行方法列表
- 是否可以在命令行中将输入参数传递给可执行文件
- 是否可以将具有不同签名的 lambda 存储在 std::vector 中并在函数中执行它们(使用各自的参数)?
- 如何将带有参数的方法传递给线程以执行?
- 运算符 new 的执行顺序和构造函数的参数
- 使用参数包自动执行dynamic_cast检查
- 执行参数未提供预期结果
- 如何查看完整的CMD执行命令,包括参数和标志?
- 命令行参数执行C 程序
- 在v8中,使用cpp对象作为参数执行js函数
- 对重载运算符参数执行隐式转换时出现编译器错误
- 如何使C++函数使用双精度参数或无参数执行
- 打开一个通过命令参数执行某些操作的函数
- 如何检查 chaiscript 中是否定义了函数以及如何使用类型化参数执行它
- 使用一个参数执行?为什么
- 基于运行时参数执行整型模板函数
- 使用c++将音频从mp4提取为mp3(不使用参数执行ffmpeg)
- Dll注射.使用参数执行CreateRemoteThread