In which file do we put non-member function in C++?

前端 未结 3 787
广开言路
广开言路 2021-01-28 15:49

What is the normal practice when it comes to non-member function in C++? Do we put them in main.cpp or header file or class implementation file, or do we make a separate .cpp fi

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-28 16:21

    General idea in pseudo code:

    if (it will be used in other cpp files) 
        put the declaration in a header file. 
        implement it in a header or a cpp file.
    else 
        if (only need it in some functions in a header file)
            if (it's a function more than N line )  // please define this N in your mind
                declare it in the same header and implement it in a cpp file
            else
                 put it in the same header file
        else // used in cpp only
            put it in the cpp file
    

    As long as it compiles, you should consider readability (easy for anyone to read) and accessibility (easy for anyone to find and debug).

提交回复
热议问题