2 use const rather than #define(Macro definition) :
#define is done by preprocessor, when the compiler gives an error on the value defined by , it's very hard to find the macro definition, because it's not in the symbol list.
ex: use const float CONST_FLOAT = 3.14 rather than #define CONST_FLOAT 3.14
Attention :
- for const pointer , you need const tow times : const char* const_name = "Auth"; But a better solution is use string: cosnt std::string const_name("Auth");
- for const member : you need it to be a const, and you need the class has the object, so you need static : class A{private: static const int Num = 5;}
- #define macro cannot define a class const member(out of scop)
- one solution : enum hack : enum{Numb = 5}; int scores[Numb];
- Use template inline to replace macro function :
- #define MAX(a,b) f((a)>(b) ? (a) : (b) )// first, you have to add () for every value!(囧)
- then look at this :
- int a = 5; b = 0;
- MAX(++a,b); //a incremented once
- MAX(++a,b+10); // a incremented twice! the times that a incremented depends on the other value ! 囧
- So it's better to use template inline :
- template<typename T> inline const T& a, const T& b){
- f(a>b?a:b);
- }
- with const, enum, inline, we can less use the macro, but #include, #ifdef, #ifndef are still used.
3 Use const whenever possible
- Const pointer, const data, const pointer pointed to const data
- const on the left of * : for data; const on the right of *:for pointer
- const ClassA * pa; ClassA const *pa; //----> a pointer pointed to a const object, this object cannot be changed
- ClassA * const pa; //----> a const pointer pointed to an object, the object can be changed
- const ClasssA * const pa //----> a const pointer pointed to a const object
- const method returned value ex:
- const Rational operator* (const Rational& a, const Rational& b)//--> why?
- (a*b) = c; //-> because how do you know you client will not do this ? (he want to do assignement(赋值) to the result of an operator!)
- const method parameter: simple, it's for avoid when you write == to =.
- const method : this method cannot modify the class members :
- class TextBook{
- public:
- getName() const; //just get, do not change
- }
No comments:
Post a Comment