文章转自:http://www.cocos2d-x.org/projects/cocos2d-x/wiki/Rules_of_translating_objc_to_cpp
Rules of translating objc to cpp
1. virtual method or not:
- It's better to declare all cpp member methods without "virtual" keyword;
- But when you're writing a cpp header file, please check if any methods of the parent class are overrided by your current work. Make sure to change them into virtual methods;
- If you inherit a virtual method from parent class, make sure that it inherits the "virtual" keyword.
2. methods of public/protected/private:
- By default, declare all member methods as "public" ;
- If any of the folowing conditions is satisfied, the method must be private;
- this method is declared in .m file;
- this method is in a category named "private";
3. member variables of public/protected/private:
- Declare all member variables as "protected", without any other choice
4. two-phase construction
- HOW TO:
- 1st-phase: set default value for all member variables in the constructor initialization list. But don't do write any logic init in the constructor.
- 2nd-phase: write logic init in a "CMyClass* init(...)" function. If the init failed, return NULL.
- WHY:
- We decided to abandon the usage of try-catch exception mechanism in C++. Do this to reduce the footprint and binary size. As the result, any exception occurring in C++ construction will not be reported to the invoker.
- WHEN:
- two-phase construction isn't force to implement in each class, but just for those classes who have logic step in initialization. In the other words, writing logical initialization in constructor IS FORBIDDEN, especially the situation may return false.
- FOR INVOKERS:
- If the class you will invoke has a "bool init(...)" function, call it immediately after construction.
download sample code: attachment:TwoPhaseConstruction.zip This project is tested in win32 enviroment via VS2008
5. property of objc
6. id
some functions in objc return "id", translate to cpp, we return this "bool" instead. In objc, you can write code just like [[MyClass alloc] init] autorelease]. you don't mind if init failed and return nil, in that case [nil autorelease] will not crash the programe. But in cpp, we return bool to prevent developers write pClass = (new MyClass())->init()->foo(). If init failed and return null, null->fool() will crash and jump out the program in cpp. In the other hand, if the return value of foo() isn't MyClass*, for example, return bool, and the invoker will lost the pointer of "new MyClass" then can't delete it from heap. That's dangerous.
must be translated to