简体   繁体   中英

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:

1) To declare it as private in the .h file and write the implementation in .cpp file.

2) To write the implementation directly in .cpp file without declaring it in the .h file.

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. If you use it in a single cpp file, declare it in an anonymous namespace in that cpp file. 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.

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. Then, when you are asked to create an A*, create a B* which is also an A* and return it. 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.

Pretty much like how COM implements IUnknown and stuff.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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