How does C + + compile the private property into public?
When you do a unit test of code that has already been written, you sometimes need to use a member method or variable that is private to the class. We do not want to change the original code, but also access to these private or protected methods, what to do with this situation?
1. Manual Replacement
Replace private with public in the original code and replace the protected with public manually.
This approach is the last thing we want to do, because it needs to change the original code.
2. Macro substitution
This method is relatively flattering, but also very useful, we can define two macros:
#define private public#define private public
This will allow all private and protected to be replaced with public. This requires you to change the test code.
3. Use the g++ parameter-D
The g++ itself has many parameter options, and the following parameters can dynamically add macro definitions or cancel macro definitions at compile time.
-dmacro
Equivalent to # define macro in C language
-dmacro=defn
The equivalent of # define MACRO=DEFN in the C language
-umacro
Equivalent to #undef macro in C language
Therefore, we can compile this way:
CPPFLAGS=-Dprotected=public -Dprivate=public $(CC) $(GTEST_CPPFLAGS) $(CPPFLAGS) -g -c src/inifile.cpp
The essence and method of this method are identical, and all are replaced by macro private,protected to public. The biggest difference is that this method does not have to change the original library code or test code. And only to change the makefile on it.
An example is attached below:
Examp.cpp
#include <iostream>using namespace STD;//#define PRIVATE Public//#define PROTECTED Publicclassfoo{Private:voidShow () {cout<<"I ' m private show!"<<endl;}};classfootest{ Public:voidTest () {Foo F; F.show (); }};intMain () {footest T; T.test ();return 0;}
Makefile
CPPFLAG +=-Dprotected=public -Dprivate=publicall: g++ $(CPPFLAG) -g -o examp examp.cpp
Welcome to visit
My Site----butterflies Suddenly blog Park----People are both nameless columns.
If you have any questions in the process of reading this article, please contact the author, please specify the source of the reprint!