简体   繁体   English

如何在C ++中向标准库添加我们自己的函数

[英]How to add our own function to standard library in C++

I want to add my own function to the standard library in because when I want to use this function in another program. 我想将自己的函数添加到标准库中,因为当我想在另一个程序中使用此函数时。 Then I can use them easily by just including the header then it can save me time and there is no need of rewriting the function again. 然后,只需包含标题即可轻松使用它们,这可以节省我的时间,并且无需再次重写该函数。

NEVER, EVER, EVER edit the standard library!!! 永远,永远,永远编辑标准库!!! Some compilers may not even use them, so if you #include <cmath> , it may not even use the cmath header, and use its knowledge about to standard library to make the math functions available. 一些编译器甚至可能不使用它们,因此,如果您#include <cmath> ,它甚至可能甚至不使用cmath标头,并使用其有关标准库的知识来使数学函数可用。 Even if it doesn't do that, it will increase the size of any other programs that use that header, even if they don't use your function. 即使不这样做,也会增加其他使用该标头的程序的大小,即使它们不使用您的函数。

But I still don't want to rewrite my function! 但是我仍然不想重写我的函数!

You don't have to. 不用了 You can add your own header into the include paths of your compiler (typically /usr/include on *NIX), and include it like any other standard header. 您可以将自己的标头添加到编译器的包含路径中(通常在* NIX上为/usr/include ),并像其他任何标准标头一样包含它。 Or, you could save your function in a file in the directory of a file that needs it, and #include it like this: 或者,您可以将函数保存在需要该函数的文件的目录中,并像这样#include

#include "my1.h"

Conclusion 结论

Don't edit the standard headers. 不要编辑标准标题。 Just add your own. 只需添加您自己的。

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

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