Objective
In the process-oriented language, such as C, #define is very common, and indeed useful, it is worth advocating. But in today's object-oriented languages, such as the C + + language, #define should be used sparingly.
Why is it less used in C + +?
This is because #define mechanism is simply a substitution of characters, so that you cannot add some C + + syntax elements to #define definition, thus limiting the power of the object-oriented programming language;
On the other hand, the compiler cannot get a variable type/function type that you define, so you cannot provide a comprehensive detection mechanism, resulting in more hidden bugs.
So think of the idea of replacing #define mechanism.
Idea one: Use class variables instead of macro global variables
Steps:
1. Declaring a static member within a class definition
2. Initialize the member within the class's implementation file
3. Any object derived from this class can access this member.
Example code:
1#include <iostream>2 3 using namespacestd;4 5 classCA6 {7 Public:8 Static Const floatA;9 };Ten One Const floatCa::a =5.0; A - intMain () - { thecout << ca::a <<Endl; - -Cin.Get(); - + return 0; -}
idea two: Global constants to be used in class definitions using enum implementations
In idea one, if a class CA is going to use a, such as a class to declare an array, the following statement is illegal: int arraya[a];. Why? Because in the header file of the class definition, the compiler also gets the specific value of a. Therefore, the so-called enum hack approach can be used to solve this problem.
1 enum {arraynum=5 }; 2 int Array[arraynum];
idea three: using the template inline function instead of the macro function
A very important function of the preprocessor is to implement macro functions, such as the following macro function can return a and b larger values between A and B regardless of the specific type:
1 #define Call_with_max (A, B) f ((a) > (b)? ( A):(B))
But there are several loopholes in this implementation, and readers are not trying to find out for themselves.
Instead of using the template inline function, you can add a variety of syntax mechanisms, such as defining it as a member function of a class, without these vulnerabilities. The following code demonstrates the specific approach of the template inline function to implement the change function:
1 template <typename t>2void Callwithmax (constconst T &B) 3{4 f (a>b? A:B); 5 }
Summary
These three ideas can be replaced #define a lot of times.
However, #define does not completely exit the stage, and the conditional compilation functionality It provides is now very useful.
The first: As much as possible to replace the #define with Const/enum/inline