Вопрос

I was reading some tutorials and making a code but met a simple weird function method that a void function with just parameter type not actual parameter like: "void foo(int)".

I know that if I make a code like "void foo(void)" that means it definitely doesn't allow me to pass parameters but have no idea what means if parameter has just type 'int.' It wasn't even a function declaration, but a function definition.

First, I thought it may mean I can pass any int variable but it wasn't. If anyone knows this, could you please teach me what this is about? Thank you for reading and your time. The code is below:

struct SA{
void display()  { cout << "struct sA without int" << endl; }
void display(int) { cout << "Struct sA" << endl; } // this is it. I have no idea what means putting just type int. I can't even use this function
};

int main(){
    SA sa;
    sa.display(); // I had no problem to call display() but have no idea how to use diplay(int)
}
Это было полезно?

Решение

You could simply pass an integer to it. It doesn't use it, but that doesn't matter in this context.

sa.display(0);

Such an approach may be useful in the real situation if you intend to have this function overloaded in the child classes, where this integer will actually be used.

Другие советы

The name of the parameter is optional really. The declaration void display(int) is perfectly normal if the parameter will not be used in the function body.

In order to call this method just pass any int as a parameter.

A name is only needed if you use it. Since the parameter is not used in the method, not providing name will not cause any problem.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top