简体   繁体   English

在main.cpp中而不是在头文件中定义函数是不好的做法吗?

[英]Is it bad practice to define functions in main.cpp rather than in header files?

Is it bad practice to define functions in the file containing the main function rather than header files and their corresponding .cpp file? 在包含main函数的文件中定义函数而不是头文件及其相应的.cpp文件是不好的做法吗? What I currently do is declare my function prototypes at the beginning of the file before the main function and then define the functions at the end after the end of my main function. 我目前所做的是在main函数之前的文件开头声明我的函数原型,然后在main函数结束之后定义函数。 Would an employer consider this to be noobish? 雇主会认为这是不道德的吗?

It's good practice to keep everything as local as possible. 将所有内容尽可能保持在本地是一种很好的做法。 If the functions are not accessed outside the .cpp file, don't put them in the header file (you may want to put local helper functions in an anonymous namespace, though). 如果不在.cpp文件之外访问这些函数,请不要将它们放在头文件中(您可能希望将本地帮助函数放在匿名命名空间中)。

It all depends on what you're doing, for instance if you're working on a project that's going to make use of classes you may want to move them into a separate header file and or .cpp especially if you plan on reusing the functions and classes you've made. 这一切都取决于你正在做什么,例如,如果你正在开发一个将要使用类的项目,你可能希望将它们移动到一个单独的头文件和.cpp,特别是如果你打算重用这些函数和你做过的课程。

If the project is small than you really don't have to worry about it and it's neither correct nor incorrect at that point (and in general) you should try to be as efficient as possible and each situation is different so you have to look at each one when you come to it :) 如果项目很小,你真的不必担心它,那时它既不正确也不正确(一般而言)你应该尽可能高效,每种情况都不同所以你必须看看当你来到它时每一个:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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