0

当涉及到 C++ 中的非成员函数时,通常的做法是什么?我们是将它们放在 main.cpp 或头文件或类实现文件中,还是我们为它制作一个单独的 .cpp 文件?如果正常的做法是单独做一个文件,那我们把非成员函数头(prototype)放在哪里呢?它只在 main.cpp 中还是在它们两者中?

4

3 回答 3

4

我想说您不应该将非成员函数与类和成员函数以及其他符号区别对待。

您应该为应用程序的每个逻辑组件(模块)创建不同的头文件 .h和相应的源文件。 .cpp

所有公共符号都应该在头文件中声明/定义(无论它们是非成员函数还是其他),所有非公共符号和所有必需的定义都应该放在源文件中。

简而言之,根据逻辑程序组件进行分组,而不是按符号/函数的类型。

于 2017-05-03T00:11:15.953 回答
0

您的班级应该有自己的 .cpp 文件。非成员函数应该放在其他文件中(全部放在一起或根据相似性分组)。这是北美的惯例,但惯例不同。原型只需要进入头文件,这样你就可以在任何地方使用它。

于 2017-05-03T00:01:17.667 回答
0

伪代码中的一般思想:

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

只要它可以编译,您就应该考虑可读性(任何人都易于阅读)和可访问性(任何人都易于查找和调试)。

于 2017-05-03T00:27:22.110 回答