===========================================
classic practice of OOP
An example:
Effective rules vary in the sublanguages.
prefer compiler to preprocessor
preprocessor replace; compiler could repace(better tail-after, more visulization)
if not, the replaced ones are difficult to watch and debug. Especially when it’s in another file written not by myself.
const char* const kBloggerName = "Honour-Van"
class GamePlayer{
private:
static const int NumTurns = 5; // only declaration
int scores[NumTurns]; // using the const
}
On condition that we need to take address or compiler wrongly insisted, we need:
const int GamePlayer::NumTurns;
Tips: we seldom initialize vars in classess, except for const
s
because we may declare several times, but only implement only once(during which we alloc the address to the vars.)
if our attempt to initialize the const we stated above or use the static const to declare the array is FAILED(this is totally to blame for the foolish compiler), we can use the enum hack to compensate.
in the link on the runoob, enum hack is described as a seldom used technique.
advt:
static const int
var, without troubling CE.macros look like functions but that don’t incur the overhead of a function call.
but macro functions often made things foobar.
// call f with the maximum of a and b
#define CALL_WITH_MAX(a, b) f((a) > (b) ? (a) : (b));
int a = 5, b = 0;
CALL_WITH_MAX(++a, b); // a is incremented twice
CALL_WITH_MAX(++a, b+10); // a is incremented once
using inline template functions
template<typename T> // because we don't
inline void callWithMax(const T& a, const T& b)
// know what T is, we
{ // pass by reference-to
f(a > b ? a : b); // const
}
const
whenever possiblechar greeting[] = "Hello";
char *p = greeting; // non-const pointer,non-const data
const char *p = greeting; // non-const pointer, const data
char * const p = greeting; // const pointer, non-const data
const char * const p = greeting; // const pointer, const data
the only key is the order of const
and *
,
but the order of const and data type doesn’t count:
void f1(const Widget *pw); // f1 takes a pointer to a constant Widget object
void f2(Widget const *pw); // so does f2
iterators:
iterator | pointer declr | figurative |
---|---|---|
const |
T* const p |
target |
|
const T* p |
camera |
mainly when dealing with the user-type
often used as interface.
if we want to change a specific member in the const function, you’d use the mutable
keyword