4. Function overloading in C ++, C ++ calls C Code, new/delete keywords, namespace (namespace), 4. cnamespace

Source: Internet
Author: User

4. Function overloading in C ++, C ++ calls C Code, new/delete keywords, namespace (namespace), 4. cnamespace

Main content of this chapter:

  • 1)Function overload
  • 2)C ++ calls C code
  • 3)Dynamic memory allocation using the new/delete keyword
  • 4)Namespace

As we all know, in life, the combination of verbs and different nouns will have different meanings, such as "playing ":

  • Play games
  • Card games
  • Play football

So in C ++Function overload(Function Overloading is available in JAVA, c #, and other languages)

1. Function overload)

Indicates that multiple function names have the same name (similar to the above "play"), but the parameter table is different (similar to the above verb)

Different parameter tables mainly include the following types:

  • 1)Different number of parameters
  • 2)Different parameter types
  • 3)Different Parameter order

1.1 example

#include <stdio.h>int func(char *str)      //func1{   printf("str=%s\n",str);  }int func(int a)            //func2{   printf("a=%d\n",a);}int func(int a,int b)   //func3{   printf("a*b =%d\n",a*b);}int main(){ char s[10]="hello"; func(s); func(10); func(5,5);           }        

Output result:

str=helloa=10a*b =25

From the previous example, we can see that the function name is the same, the parameters are different, but the meaning is quite different.

 

1.2 are the entry addresses of these overload functions the same?

Modify the main () function of the chestnut, as shown in:

The output result is displayed. The entry address of each function is different (the entry address of the overload function must be obtained through forced conversion)

You can also run the nm command to view the symbol table, as shown in:

 

 

Note:

  • Need to overload the FunctionAvoid usingDefault Value
  • When you call an overloaded function, only the function will be matched.Parameter table, And functionsReturn ValueIrrelevant
  • Function overload must occur inSame ScopeMedium
  • The entry address of the overload function, which cannot be obtained directly by the function name.

 

2. C ++ and C code call each other

When C ++ wants to call a function in C, use the extern "C"

For example, use C ++ to call the add () function in C.

1)Create 3 files first

 

Add. cThe Code is as follows:

#include "add.h"int add(int a,int b){  return a+b;}

 

Add. hThe Code is as follows:

int add(int a,int b);

 

Main. cppThe Code is as follows:

# Include <stdio. h> # ifdef _ cplusplusextern "C" // compile add in C mode. h, that is, add () function {# include "add. h "}# endifint main () {printf (" % d \ n ", add (1, 3); return 0 ;}

In main. cpp_ CplusplusMacroC ++ compiler, andExtern "C"Only C ++ is defined.

So pass_ Cplusplus macroMake sure that main. cpp can be compiled and run in C or C ++ compiler.

2)Compile and run:

Gcc-c add. c // generate the add. o file g ++-o main. cpp add. o // generate the main executable file./main

3)Output result:

 

 

3. Dynamic Memory Allocation in C ++

3.1 Review C:

In C language, we all know thatMalloc ()AndFree ()For example:

Int * p = malloc (10 * sizeof (int); // apply for 10 int-type space if (p) {...... free (p );}

From the examples above, we can see that C allocates memory through the library function.

 

3.2 In C ++, The new Keyword is used for memory application, and the delete keyword is used for memory release, for example:

  • Type:Exponential data types, such as int, char, and float
  • N:Size of the number of arrays requested

In addition to examples, you can use the new KeywordAllocate and initialize(Similar to the calloc () function)

For example:

Int * p1 = new int (1); // dynamically allocate an int space to p1 and assign it to 1 float * p2 = new float (2.0f ); // f is added to 2.0, indicating that 2.0 is a float char * p3 = new char ('C ');

Note:

  • When releasing the array space, you must useDelete []To avoid Memory leakage

 

4. namespace in C ++)

4.1 Review C:

As we all know, when compiling multiple C files in C language, you may encounter an error with a global identifier of the same name, because all the global identifiers in C language share the same scope.

 

4.2 therefore, the namespace concept is proposed in C ++.

  • The namespace will apply the global scopeDivided into different partsCan aggregate classes, objects, and functions in a namespace.
  • Different namespacesIdentifier inIt can have the same name.
  • Yes.Mutual nestingThat isACommand SpaceCan be further definedB Command Space
  • In C ++, the global scope is also calledDefault namespace

4.3 namespace usage

1)Define a namespace:

Namespace name // define a namespace named name {int varialbe ;//......}

2)Use the entire namespace:

using namespace name;   

3)Use the variables in the entire namespace:

::varialbe;     

4)Use the variables in a namespace:

Using name: variable // use the variable in the name Space

 

4.4 example

# Include <stdio. h> namespace First // define the First namespace {int I = 0;} namespace Second // define the Second namespace {int I = 1; namespace Internal // in Second, define an Internal space (nested) {struct Position {int x; int y ;}}} int main () {using namespace First; // use the entire namespace of First, become the default space using Second: Internal: Position for this main (); // use the Position struct printf ("First :: I = % d \ n ", I); printf (" Second: I = % d \ n ", Second: I); Position p = {2, 3 }; printf ("p. x = % d \ n ", p. x); printf ("p. y = % d \ n ", p. y); return 0 ;}

Output result:

First::i = 0Second::i = 1p.x = 2p.y = 3

 

To be continued, continue to study the forced conversion in C ++ in the next chapter.

 

 

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.