我知道函数调用中存在歧义.有没有办法调用foo()函数
I understood that there is an ambiguity in a function call . Is there a way to call foo() function?
#include< iostream >
using namespace::std;
int foo(); //function with no argument
int foo(int=10); //Default argument
int foo()
{
cout<<"n Foo , I am foo n";
return 0;
}
int foo(int f)
{
cout<<"n I am Foo too.n";
return 0;
}
int main()
{
foo();
foo(2);
cin.get();
return 0;
}
没有干净的方法,只有丑陋的方法。例如:
static_cast<int (*)()>(&foo)();
或者:
int (*p)() = &foo;
(*p)();
最重要的是,由于模糊性,您不能依赖过载解决方案。因此,您需要使用这种方法明确地解析符号。
首选的解决方案是首先避免出现不明确的过载。通常可以找到一些合理的方法来做到这一点,但方式取决于实际细节。
您可以显式强制转换函数指针,但不确定是否应该强制转换。
#include <iostream>
using namespace::std;
int foo(); //function with no argument
int foo(int=10); //Default argument
int foo()
{
cout<<"n Foo , I am foo n";
return 0;
}
int foo(int f)
{
cout<<"n I am Foo too.n";
return 0;
}
int main()
{
static_cast<int(*)()>(foo)();
foo(2);
cin.get();
return 0;
}
编辑:
这一行static_cast<int(*)()>(foo)();
只是对函数的强制转换和调用的缩写形式。
为了解释它,我们可以通过三个步骤将其拆开:
将myFuncType定义为指向返回int且不接受参数的函数的指针
using myFuncType = int(*)();
通过将重载名称foo强制转换为不带参数的函数类型来解决该名称,并将其存储在名为f 的变量中
auto f = static_cast<myFuncType>(foo);
// or auto f = (myFuncType)foo;
// or auto f = (myFuncType)&foo; C++ actually does the address-of implicitly with functions
最后一个是调用函数指针
f(); //or (*f)(); C++ automatically dereferences function pointer on call, but you can also manually dereference
- 删除默认参数,或者
- 重命名其中一个函数
不清楚为什么这两个函数声明使用相同的名称。只有当他们应该"做同样的事情"时,你才应该这么做。
删除默认参数
如果这两个函数应该做相同的事情,那么:
当你为一个函数指定一个默认参数时,你会得到一个额外的函数签名
int foo(int arg=10);
还可以给你
int foo();
它说,对于*对foo()
的任何调用">",arg的值都是10
。
但是,您已经加入了一个额外的int foo();
,它返回0
,这让编译器感到困惑。在更抽象的层面上,您实际上混淆了自己关于函数应该做的"事情"的默认参数是什么。
重命名其中一个函数
如果这两个函数不做相同的事情,它们就不应该有相同的名称。有几种不同的方法可以做到这一点:
- 为一个新名字
- 将其中一个放在命名空间中
- 使用模板
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 函数调用中参数的顺序重要吗
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在c++类上调用void函数
- 我知道函数调用中存在歧义.有没有办法调用foo()函数
- 没有用于调用 foo 的匹配函数
- 如何在C++中调用void foo(int (&)[]) {}?
- 为什么我需要双括号在构造函数调用中,如:foo x((bar());
- 让 foo(derived_object) 调用 foo(Base const&) 而不是模板函数?
- 为什么Foo({})调用Foo(0)而不是Foo()
- Foo(Foo x){}是否会在C++中被调用
- 为什么"foo f();"不调用类的构造函数"foo"?
- C++11 标准中的哪个子句支持在下面的函数 foo() 的返回中调用移动构造函数
- 没有匹配的函数调用Foo::Foo
- C++。无法调用成员函数。错误 : "foo is private"
- c++:为什么调用 foo(X&) 而不是 foo(X&&)?