简体   繁体   中英

Function Declaration Parameter Naming Best Practices (C++)

In a function declaration, while the parameters do not have to be named, is it preferable to have them named? What are the advantages and disadvantages of this?

The advantage of naming them is that you can refer to them in the documentation. (This includes your editor/IDE picking them up and presenting them to you as hints when you type a call to such a function.)

A disadvantage would be that names might change according to the function's implementation, except for the fact that the names in a function declaration might differ from those in the function's definition. (IOW: I see no disadvantage.)

主要是出于文档原因

Naming parameters has a significant advantage when you work with IDEs that support auto-completion. When you start typing the name of your function, the IDE pops up a list of suggestions. Seeing findUser(string firstName, string lastName) tells you a lot more than simply findUser(string,string) .

This is more of a question of style. Personally, if I see a function declaration without named parameters, I find it hard to read. I think the more strong you can type C++, the better it is.

One advantage is that they can convey more information when parameter types are the same

Consider

CoordSystem CreateCoordinateSystem( const UnitVector& xdirection, 
    const UnitVector& ydirection, const UnitVector& zdirection
)

over

CoordSystem CreateCoordinateSystem( const UnitVector& , 
    const UnitVector& , const UnitVector& )

In the declaration there aren't really any programmatic advantages or disadvantages. However, there is one style advantage that I can think of:

When you don't use a parameter in a function, you can not name this parameter in the declaration AND the definition:

void foo(int);

void foo(int)
{
}

Naming parameters that you don't use in the definition isn't illegal, but it is a lint warning! The style advantage that I mentioned would be not naming the parameters in the declaration so that someone who is browsing a header file will know that a certain parameter is not being used in the definition. However, this is only if you synchronize the not-named-ness between the definition and the declaration.

Here's an example of when you might want to not name a parameter:

class Base
{
    virtual void foo(int a) = 0;
};

class Child1
{
    virtual void foo(int a) { std::cout << a + 1 << std::endl; }
};

class Child2
{
    virtual void foo(int) { std::cout << "mwahaha" << std::endl; }
};

In this case, the parameter isn't named, but still must be supplied because the function prototype must match that of its parent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM