![](/img/trans.png)
[英]How do I call a member function inside a non-member function in C++ with an object created outside the non-member function?
[英]In which file do we put non-member function in C++?
关于C ++中的非成员函数,通常的做法是什么? 是将它们放在main.cpp还是头文件或类实现文件中,还是为它制作一个单独的.cpp文件? 如果通常的做法是制作一个单独的文件,那么我们将非成员函数标头(原型)放在哪里? 它只进入main.cpp还是同时进入两者?
我要说的是,您不应将非成员函数与类,成员函数和其他符号区别对待。
您应该为应用程序的每个逻辑组件 (模块)创建一个不同的头文件 .h
和一个相应的源文件 .cpp
。
所有公共符号都应在头文件中声明/定义(无论它们是非成员函数还是其他非成员函数),所有非公共符号和所有必需的定义都应在源文件中 。
简而言之,根据逻辑程序组件进行分组,而不是根据符号/功能的类型进行分组。
您的班级应该有自己的.cpp文件。 非成员函数应放在其他文件中(全部或根据相似性分组)。 这是北美的惯例,但惯例有所不同。 原型只需要放在头文件中,这样您就可以在使用它的任何地方包括它。
伪代码的一般思路:
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
只要可以编译,就应该考虑可读性 (任何人都容易阅读)和可访问性 (任何人都容易找到和调试)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.