简体   繁体   English

class 中的 C++ 辅助函数,如何使用它们?

[英]C++ helper functions in class, how to use them?

In my class in C++ I want to write a helper function (Which external users can't see or use) and found 2 ways to do that:在我的 C++ 中的 class 中,我想编写一个帮助程序 function (外部用户无法看到或使用)并找到了两种方法:

1) To declare it as private in the .h file and write the implementation in .cpp file. 1).h文件中将其声明为私有,并在.cpp文件中编写实现。

2) To write the implementation directly in .cpp file without declaring it in the .h file. 2)直接在.cpp文件中编写实现而不在.h文件中声明。

What's the correct way, the difference or the advantage one have on the other?什么是正确的方法,一个人对另一个人的区别或优势是什么?

Since you are not exposing this function through your interface, you should not declare it in the public header file.由于您没有通过接口公开此 function,因此不应在公共 header 文件中声明它。 If you use it in a single cpp file, declare it in an anonymous namespace in that cpp file.如果您在单个 cpp 文件中使用它,请在该 cpp 文件的匿名命名空间中声明它。 If you use this function in multiple cpp files but you would still like to not make it a part of your interface, you can create internal header files that you #include in your source files, but aren't a part of your library's public interface.如果你在多个 cpp 文件中使用这个 function 但你仍然不想让它成为你界面的一部分,你可以创建内部 header 文件,你可以在源文件中#include ,但不是库的公共接口的一部分.

The way is to create a class A that would be visible to the public, then create a descendant class B of this class and implement it privately.方法是创建一个对公众可见的 class A,然后创建此 class 的后代 class B 并私下实现它。 Then, when you are asked to create an A*, create a B* which is also an A* and return it.然后,当你被要求创建一个 A* 时,创建一个也是 A* 的 B* 并返回它。 Your code sees a B* but the user of the class sees A* and may only access methods and variables declared in A. You also need to create/destroy your pointers with some function rather than with new/delete.您的代码看到 B*,但 class 的用户看到 A*,并且只能访问在 A 中声明的方法和变量。您还需要使用一些 function 而不是使用 new/delete 创建/销毁指针。

Pretty much like how COM implements IUnknown and stuff.很像 COM 如何实现 IUnknown 之类的。

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

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