C + + try not to use #define instead of using const, enum, inline replacement. _c language

Source: Internet
Author: User
Tags constant
For example: Here the program file starts with the following #define statement

Copy Code code as follows:

#define N 10
#define PI 3.14
#define MAX 10000
#define HEIGTH 6.65
...
...


Let's say the program is running an error, and if we have errors using these constants, the editor should throw an error message. If this message prompts 6.65 there is an error, OK if you are lucky you happen to remember or a simple look can find 6.65 represents what, if the program is complex, and 6.65 of the file is referred to the file, do not remember, then you will be puzzled what this is? It might take a lot of time to track down what 6.65 is? And then locate the problem.
Why is the error message 6.65? And not Heith? Because in the precompilation phase, 5.65来 has been substituted for heigth,height without entering the notation table (system table). The solution is to replace it with the following statement
const double treeheight=5.68;
As a language constant, Treeheight will surely be informed by the compiler and enter the notation table. The error is not a number but a variable name, which is helpful in locating the problem.
Here, specifically, there are two special cases of constant substitution #define.
The first is to define a constant pointer. Here you define the pointer as a constant pointer, which also points to a constant, so it is in the following form:
const char * const hz= "Hang Zhou";
It is best to use a string object in C + + to replace the char* form:
Const std::string HZ ("Hang Zhou");
The second notable is the class-exclusive constant. The first is used to restrict to a class, and it must be declared as its member. Second, make sure that the constant has at most one entity, and that it must be called a static member. For example:
Copy Code code as follows:

class people
{
Private
static const int number=10;
int Phonenumbers[number];
......
}

This is a declarative, not a defined, expression. C + + usually requires you to provide a definition of anything you use. Alternatively, use an enum to replace the macro of a formal function with inline or template as much as possible. But if it is a class-specific constant and is static and is an integer type (int,char,bool), special handling is required. As long as you do not marry their addresses, you use only declarations without providing a definition formula. However, if you take the class-specific constant address, you should provide a definition formula even if you do not take its address compiler.
static const int People::number
This definition does not set an initial value because the declaration has already acquired the initial values.

You can use an enum to do something similar here
Copy Code code as follows:

class people
{
Private
enum {number = 10};
int Phonenumbers[number];
....
}

Enums are more like #define than Const. Because the address of the const is legal, it is illegal to take an enum's address, and it is usually illegal to take the #define address. So you can use an enum to implement an address that does not let others get a constant.

Here are a few written questions
Copy Code code as follows:

#define PRODUCT (A,B) a*b
....
int a=5,b=3,c;
C=product (A+3,B+4);

So what is the value of C? C=5+3*3+4=18 rather than the 56 expected by the programmer, if you want to achieve the desired results you have to write

#define PRODUCT (A,b) ((a) * (b))
Perhaps you will insist on writing macro functions, because you want to say that only by writing a macro function can complete the int,flaot,double and other types of product operations. So take a look at the following example

#define MAX (A,b) ((a) > (b)? ( A):(B))

int a=5,b=3

MAX (++A,B); A was added twice.

MAX (++A,B+4); A was added once.
A added result may not be expected, you can use the template inline function to achieve the expected effect of the macro, and the efficiency is similar to the macro.
Copy Code code as follows:

Template<typename t>
inline void Max (const t& a,const t& B)
{
f (A>B?A:B);
}

The inline function is a compilation mechanism that is somewhat invisible from the code, however, there is a difference in the efficiency of the execution of a program, usually the compiler's handling of a function call is a similar way of breaking, that is, when executing to a function call statement, all of the current information is stored in the register to execute the function's code. Retrieve the Register value after execution, revert to the state where the call function started, and continue executing the code. When declared as a inline function, the compiler does not compile the function into a calling function but copies the code to the place where it was invoked. So the efficiency is higher than the ordinary function, less the register and register information to take the steps.
Also note that the inline function is best written to the. h file, or written directly to the class.
Const allows the programmer to specify a semantic constraint that cannot be altered, and the compiler enforces this constraint. It indicates that the value modified by it is invariant. Const can modify constants in global or namespace scopes outside of classes, or modify files, functions, or static objects and pointers. In the const application in the pointer to notice where the keyword const appears in "*", if the left side indicates that the value being pointed to is a constant, if the pointer itself is a constant on the right. There is a set of features on both sides representing both. Here are some special words:
(1) cosnt in the iterator
Const Std::vector<int>::iterator Iter=vec.begin (); The equivalent of ITER can not change

Std::vector<int>::const_iterator Citer=vec.begin (); The content that ITER is pointing to cannot be changed.
(2) Declaring a function return value as a constant not only reduces the unpredictable circumstances caused by the programmer's error, but also does not have to give up security and efficiency. For example:

Const Operater * (const &lhs,const &AMP;RHS);
if ((A * b = c);/is intended to be if (A*b==c) is written in this way by programmers sloppy
If both A and B are built-in types, this code is unreasonable, but it is our custom type that might work, and if the declaration return value is cosnt, it can be prevented.

(3) A const member function to confirm that a member function can be used for a const object. and two member functions can be overloaded if they are only constant. A member function, followed by a const, indicates that the function cannot change the member variables of the class (the following code verifies that the compiler will burst an error if an attempt is made to assign a value to its members). The principle is that the compiler considers it a read-only variable. And most const objects are used for reference passing or pointer passing.
Copy Code code as follows:

#include <iostream>
#include <string>

class people
{
Public
People (): M_sname (""), M_iage (0) {}
People (std::string name,int Age): M_sname (name), M_iage (age) {}
void set (int age)
{
this->m_iage=age;
}

void Set2 (int age) const
{
this->m_iage=age;
}

int get ()
{
Return this->m_iage;
}
Private
Std::string M_sname;
int m_iage;
};

int main (int argc,char **argv)
{
people* p=new people ("Sky", 8);
P->set (10);
Std::cout<<p->get () <<std::endl;
P->set2 (12);
Std::cout<<p->get () <<std::endl;
Delete p;
return 0;
}


Compiling the file will report the following error message
Const_test.cpp:In member function ' void People::set2 (int) const ':
Const_test.cpp:16:error:assignment of Data-member ' people::m_iage ' in read-only structure
Const_test.cpp:36:2: Warning:no newline at end of file
Cosnt Overload (Note: If a formal parameter is a reference or a pointer, the formal parameter will have an effect if it is a const). You can try it. We remove the & of the following code, and the incoming const_int actually calls the void set (int age) function, stating that the const of the formal parameter does not work. Here is the validation code
Copy Code code as follows:

#include <iostream>
#include <string>
class people
{
Public
People (): M_sname (""), M_iage (0) {}
People (std::string name,int Age): M_sname (name), M_iage (age) {}
void Set (const int& age) const
{
std::cout<< "This is const" <<std::endl;
}

void Test (int& age)
{
std::cout<< ' This is Non-const ' <<std::endl;
}

void Test (short age)
{
std::cout<< ' This is Non-const ' <<std::endl;
}

int get ()
{
Return this->m_iage;
}
Private
Std::string M_sname;
int m_iage;
};

int main (int argc,char **argv)
{
people* p=new people ("Sky", 8);
const int const_int=12;
P->test (Const_int);
Std::cout<<p->get () <<std::endl;
Delete p;
}

(4) The problem of duplication of overloaded function code. By experience we can conclude that the functions that are overloaded by const often have a lot of code that is repetitive, even the same. If most of the code repeats, we can write the duplicate code as a function, which is called separately. If it is the same as the following code, we can call the const function in the NON-CONST function to resolve the code duplication.
Copy Code code as follows:

class people
{
Public
People (): M_sname (""), M_iage (0) {}
People (std::string name,int Age): M_sname (name), M_iage (age) {}
void Eat (const people & person) const
{
std::cout<< "this person info is:{age =" <<person.m_iage () << ", name =" <<person.m_sname () < <std::endl;
std::cout<< "eating" <<std::endl;
std::cout<< "End" <<std::endl;
}

void Eat (people & person)
{
std::cout<< "this person info is:{age =" <<person.m_iage () << ", name =" <<person.m_sname () < <std::endl;
std::cout<< "eating" <<std::endl;
std::cout<< "End" <<std::endl;
}
Private
Std::string M_sname;
int m_iage;
};

Then convert the *this type from people& to const people& in the non-const eat function so that it calls the Const function, which is the function overload
Copy Code code as follows:

#include <iostream>
#include <string>
class people
{
Public
People (): M_sname (""), M_iage (0) {}
People (std::string name,int Age): M_sname (name), M_iage (age) {}
void Eat (const people & person) const
{
std::cout<< "this person info is:{age =" <<Person.m_iAge<< ", name =" <<Person.m_sName<< "} "<<std::endl;
std::cout<< "eating" <<std::endl;
std::cout<< "End" <<std::endl;
}

void Eat (people & person)
{
Static_cast<const people&> (*this). Eat (person);
}
Private
Std::string M_sname;
int m_iage;
};

int main (int argc,char **argv)
{
People person ("sky", 8);
Person.eat (person);
}

The result of the run is

This person info is:{age =8,name =sky
Eating
End
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.