Experience Sharing from C to C ++ (2)

Source: Internet
Author: User

C ++Although the technology is very fashionable, many C users want to label themselves as C ++ in the shortest time. There are a lot of books about C ++, but only those users who are lucky enough to get started will occasionally flip over. There are still a lot of hooligans wandering at the door of C ++.

This article only targets C users, preferably a very good old user. For example, he tries to use pointers when encountering the simplest problem ), through some C and better C ++, this article uses Borland C ++ 3.1) routines to introduce some knowledge about C ++, so that readers and friends can "dive deeper and deeper ", easy to use C to C ++!

Ii. Challenges # define

# Define is a very useful Command provided by C, but in C ++, it is very likely that macro commands are not used.

1. the const macro command allows you to specify the value of an identifier as a constant,

For example: # define PI 1415926

It can also be used to define a string: # define HZK16 "HZK16F" the following can be used through:

 
 
  1. cout << "PI is“<<PI;  
  2. cout << "Filename: "<< HZK16;  

Macro is not a legal object after all, although it is disguised as perfect. C ++ provides the constant modifier const for you to specify the value of an object as a constant. It prevents users from assigning values or other side effects,

Similar to the preceding example:

 
 
  1. const float PI=3.1415926;  
  2. char*const HZK16="HZK16F";  
  3. PI = 3. 14; //error  
  4. HZK16="HZK16K"; //error: Cannot modify a const object  

However, pointer processing seems complicated. For example, the following operations are legal:

 
 
  1. HZK16[5]=’r’; //ok HZK16 ="HZK16K" 

It is necessary to clearly understand the scope of const modification. The declaration form and corresponding meaning are as follows:

 
 
  1. Char * const cpl = "I love you! '; // Const modifier' * ', cp1 is a pointer constant pointing to a character
  2. Const char * cp2 = "I hate you! '; // Const modifier 'Char' cp2 is a pointer to a character constant
  3. Const char * const cp3 = "Get the hell out of here! "; // Const modifier 'Char 'and '*',

Cp3 is a pointer constant pointing to a character constant. Therefore, the following usage is still valid:

 
 
  1. strcpy(cpl "Oh no...“);  
  2. cp2++; 

Cpl only keeps an eye on a specific address, and it is not its responsibility to prevent the content from being rewritten. cp2 is the opposite. It does not allow you to modify the content, but it can be pointed by you (this may be worse ). Only using two modifiers (such as cp3) can be the safest way.

Pointer to const cannot be assigned to pointer to non-const:

 
 
  1. float*p=&PI;  
  2. //error: Cannot convert 'const float*’ to 'float*’  
  3. *p=3.14; 

This restriction ensures the valid meaning of constants. Note that indirect modification of constants caused by Explicit conversions is possible:

 
 
  1. // Test08.cpp
  2. # Include <iostream. h>
  3. Void main ()
  4. {
  5. Char * Spy;
  6. Const char * const String = "Yahoo! ";
  7. Spy = (char *) String;
  8. Spy [5] = '? ';
  9. Cout <String;
  10. }
  11. Output result: Yahoo!

2. inline function in line function)

Macros can obtain functions similar to functions in some scenarios. The following is a common example: # define ADD a B) a) + B ))

Cout <"1 + 2 =" <It outputs the data summation function, but we have at least one reason to refuse to use it. The following are the most obvious reasons:

① Macros lack type security detection, such:

 
 
  1. ADD 'A' 0. 0l); 

Such a call will be interpreted as legal, but in fact few users expect such a statement to be written;

② Macros do not introduce temporary copies for parameters, such:

 
 
  1. #define DOUBLE (x)((x)+(x))  
  2. int i(1);  
  3. cout<<DOUBLE(i++); //prints '3'  

③ Macros do not have addresses. For example, they may exist in a calculator program:

 
 
  1. case ' +': Operator = & ADD; 

It cannot be reasonably explained.

Take the function? However, using a function is not the most cost-effective, and it wastes valuable execution time. Readers who have used assembly languages may know that in general, some field protection work should be done before and after the real function execution, when the function volume is very small, this redundant workload will be much greater than the function itself.

Therefore, C ++ provides the keyword "inline". When you want the compiler to directly Insert the code of a function into the call point, you can set it as an inline function, add the keyword inline when defining a function, for example:

 
 
  1. //test09.cpp  
  2. #include <iostream.h>  
  3. inline int Add (int a int b)  
  4. {  
  5. return a + b;  
  6. }  
  7. void main O)  
  8. {  
  9. cout<<"1+2=“<<Add(1 2);  
  10. }  

The main function will be interpreted by the compiler:

 
 
  1. count<<"1+2=“<<{1+2 }; 

The behavior is similar to the ADD a B) Macro of the worker. Experience shows that it is wise to declare frequently used and very small functions as inline.

3. Function overload)

In actual data summation operations, the Add function provided in the above section is far from enough. You have to Add other code, such:

 
 
  1. double AddDouble(double a double b)  
  2. {  
  3. return a + b;  
  4. }  
  5. float AddFloat (float a float b )  
  6. {  
  7. return a + b;  
  8. }  

In particular, you can play with the name Technique in C ++ and name all the above AddDouble AddFloat names as Add, for example:

 
 
  1. double Add(double a double b)  
  2. {  
  3. return a + b;  

Rest assured that the compiler will safely find the corresponding function prototype for different calling forms. For example:

 
 
  1. double a b;  
  2. Add(f 2); //int Add(int int)  
  3. Add (a b); //double Add (doubledouble)  

In this way, different functions have the same function name, that is, function overloading. Function overloading and subsequent templates and virtual functions form the "one interface, multiple functions" feature, namely, polymorphism), which is one of the technologies of object-oriented OO.

When using the overload mechanism, C ++ puts forward many restrictions to prevent ambiguity, such:

 
 
  1. void fun(int a);  
  2. int fun(int a);  
  3. void fun(int& a);  
  4. void fun (int a int b=0);  

It is likely to cause a panic in the C ++ compiler, and it will be very dissatisfied when it encounters calls such as fun100. The user is obligated to ensure that any call form does not produce ambiguity. The following is a common example of using the overload mechanism:

 
 
  1. //test10.cpp  
  2. #include <graphics.h>  
  3. #include <iostream.h>  
  4. void Pixel(int x int y int color)  
  5. {  
  6. putpixel(x y color);  
  7. }  
  8. int Pixel(int x int y)  
  9. {  
  10. return getpixel(x y);  
  11. }  
  12. void main()  
  13. {  
  14. int Driver=VGA Mode=VGAHI;  
  15. initgraph(&Driver &Mode "");  
  16. Pixel(100 100 4);  
  17. int Color = Pixel(100 100);  
  18. closegraph();  
  19. cout << "Color of point(100 100):" << Color;  
  20. }  

As you can imagine, C ++ encodes the different Pixel functions above into Pixel_iii and Pixel_ii respectively. The format includes the data types of each entry parameter. Note that encoding does not contain the returned value information. Therefore, function overloading dependent on the differences in returned value types is unstable. Therefore, the connector linker can find the corresponding module without any effort. However, it may be difficult to add module connections between the new and old versions of C, because the traditional C function library does not have the bad habit of using function names, C ++ has to provide the keyword extern to ensure the security of this connection. Note that 'C' can be capitalized as follows ):

 
 
  1. extern "C" 
  2. {  
  3. void Pixel(int x int y int Color);  
  4. };  

It tells the compiler to find the corresponding Pixel module in the function library instead of being smart. While

 
 
  1. Extern "C"
  2. {// '# Include' must start another line
  3. # Include "function. h"
  4. };

The Declaration is contained in the header file function. h. All function modules adopt C connections.

I hope this article will help you. Please refer to the next 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.