문제

What's the point of initialising an unnamed C++ parameter? For example:

void foo(int = 0) {}
도움이 되었습니까?

해결책 2

I can imagine in the context of callback functions the construct might be useful:

#include <iostream>

// Please assume the callback is an external library:
typedef void (*callback_function)(int);
callback_function callback;

void foo(int = 0) {
    std::cout << "Hello\n";
}

int main() {
    callback = foo;
    callback(1);
    foo();
}

다른 팁

A declaration has no need of a parameter name. The definition does, however. Also, the default parameter cannot be repeated in the definition. Here's a small program that works (but I don't know why you would want to do something like this, really...):

#include <iostream>

void foo(int = 5);

int main() {
    foo();
    foo(3);

    return 0;
}

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

The output is

5
3

It will serve as the default parameter value. It belongs in the function declaration.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top