Effetive C + + 02 try to replace # define with Const,enum,inline

Source: Internet
Author: User

#define aspect_ratio=1.1
Const Double aspectratio=1.1

1. Using a macro causes the preprocessor to unconditionally replace the Aspect_ratio in the program code with 1.1, the compiler has never seen Aspect_ratio, debug compilation can be difficult to track, and the const constant resolves the problem.

2. The scope of the macro definition is the subsequent compilation process until it is #undef, so the macro definition cannot be used as an exclusive constant for the class, for example, we want to define an array in the class, the size of the array requires a constant, we will do this in the following way:

class test{private:    staticconstint3;  Static can guarantee that the constants have    only one entity int  array[num];}

In addition to using const to define constant values, we can also use Enum to implement

class test{private:    enum3 };  // enumeration values can be used    when int int array[num];}

3. For the macro function, we can use the inline function instead, some people say that the macro can not limit the parameter type, function is not, this can be achieved through the template function.

#define Max (b)  F ((a) > (b)? (a): (b)template<typename t>void Max (constconst t& b) {      > B? a:b)}

Effetive C + + 02 try to replace # define with Const,enum,inline

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.