【问题标题】:Why can't we call a function from a function with a default argument?为什么我们不能从具有默认参数的函数中调用函数?
【发布时间】:2015-01-17 06:34:32
【问题描述】:

程序:

#include <iostream>

void foo(void (*bar)()){ bar(); };

void foo(int a = 5)
{
    std::cout << a << std::endl;
}

int main()
{ 
    foo(foo); //Error
}

DEMO

我预计最终会调用foo(5)。相比之下,以下程序运行良好:

#include <iostream>

void foo(void (*bar)()){ bar(); };

void foo()
{
    std::cout << 5 << std::endl;
}

int main()
{ 
    foo(foo); //OK
}

DEMO

你能解释一下这个区别吗?

【问题讨论】:

  • 拥有默认参数不会改变函数的签名。如果您不提供默认参数,编译器也会在调用点添加默认参数,而不是在您尝试形成指向函数的指针时。
  • @Praetorian 那么在第一种情况下如何调用该函数?
  • 我不认为你可以。当您通过指向函数的指针时,有关默认参数的信息会丢失,但我可能错了。
  • 编译后默认参数不存在。它们只是简写,在编译期间插入。因此它们不能在运行时使用
  • @EdHeal 是否在标准中明确指定?

标签: c++ function default-arguments


【解决方案1】:

在第一个例子中,虽然 foo 有默认参数,但它的类型是 void (bar*)(int)。使用默认参数可以在不显式指定参数值的情况下调用 foo,但仍有一个 int 参数。只需自动填充其值(在编译期间)。

【讨论】:

    猜你喜欢
    • 2019-10-10
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    相关资源
    最近更新 更多