Java programmer learns the thoughts of a day and a half C + +

Source: Internet
Author: User

During college, I studied the C language of one semester, including the C language when studying data structure. At the time, the computer was just touching, and it was nothing to program. Learn in class and occasionally hit the code on the book. Sophomore next semester, I lost the need. Recently due to the needs of the work, to use the Java Native Interface, so the study of 1 days and a half of C + +, a little bit of C + + to understand, write their own understanding.

A day and a half time, also learn not much things, I mainly understand the following several questions:

1) pointer

So many years, remember in C language, the most difficult to understand, should belong to the pointer. Remember rectification's C language book (the title is what, really forgot.) However, the author rectification teacher, the vast majority of Chinese developers should know that most of the previous use of the basic data type (that is, the native type in Java), a small part of the latter suddenly spoke of the pointer, then immediately blindfolded. But in the end still understand the pointer, although later forgot.

What is a pointer?

A pointer is a variable that holds the address of something else. A pointer is a variable that refers to a variable that has a special effect called a pointer. Its special function is to store the memory address of another thing. This means that the value of the pointer variable represents an address, which is something else. What's the other thing? is the object (or instance) we are talking about. In C + +, you also have an alias for this object: reference.

To summarize, the pointer variable points to an object (or reference).

*, the use of &

In the declaration statement:

* Indicates that the pointer,& represents a reference.

The declaration statement, either a variable declaration or a function declaration, can be described here. In a function declaration, a return value, a function name, and a parameter can all be declared as pointers.

When you use a pointer variable,

(* variable name) represents a Fetch object. (& Reference) represents the pointer.

voidPersontest (Person *p) {    if(p!=NULL) {P->setaddress ("Bei Jing, Hai Dian");//assigning values in the form of pointers(*p). SetName ("Fang Jinuo");//assigns a value in the way the object is used. (*p). Setage ( at); printf ("Show info:\n%s\n", (*p). toString ()); Deletep; P=NULL; }}


function pointers, pointer functions

This two words eight words, do not know how many people carry a somersault, actually very good understanding. The Chinese speak, mostly in the way of narration. The two words are omitted, but the auxiliary word is omitted.

The full name of the function pointer is : The function name is a pointer.

The full name of the pointer function is a function that returns a pointer to the value.

In both of these, the pointer function is easy to understand:

char * func (char[] p); This function is a pointer function.

function pointer, the function name is a pointer. Pointers are also variables, so it can be understood that the function name is a variable.

The following is a declaration of a function pointer variable:

typedef INT (* func) (int x);

This variable is then used as a parameter to another function:

typedefint(*func) (intARG);//define a function pointer/*the implementation of a function pointer * Funcimpl can be assigned as a value of func. */intFuncimpl (intArg) {    returnArg;}/** Declaring a function that takes a function pointer as a parameter to a function call*/voidCall (func f) { for(intI=0; i<Ten; i++) {cout<< f (i) <<Endl; }}//to testintMainintargcChar*args[]) {call (Funcimpl);}

The result of the program execution is 0 to 9 printing.

This function pointer has the same effect as the following JavaScript code:

function funcimpl (int  num) {    return  num;} (function call (f) {    if(f) {        if(f instance function) {              for (int i=0; i<10; i++) {               alert (f (i));}}}     ) (Funcimpl);

Of course, the same is true with the following Java code code:

Interfacecallback{intDocall (intnum);}Static voidCall (Callback Callback) {if(callback==NULL)return; for(inti=0; i<10; i++) {System.out.println (callback (i)); }}public static void Main (string[] args) {Call (NewCallback () { Public intDocall (intnum) {          returnnum; }     });}

In C #, it has another name, delegate.

In fact, they are the legendary hook function callback.

2) header file, #include

When I was in college, I didn't write too much, and I didn't look over the papers. So the head file has been a mystery to me. However, after learning Java, C #, it is natural that the # include header file will be understood as import, using, and so on.

So what does it say in the header file?

In general, the Declaration (the field in the class, the declaration of the method) is written in the. h file, and the implementation of the method is written in the CPP file. To achieve the separation between the interface and the implementation. When you use # Include in other places, you'll only see the declarations in the. h file, and you won't see a specific implementation.

Another thing to say is the two ways of # include. such as # include <xxxx.h>, #include "xxxx.h". Either way, there is a difference between the,<> method is to find the. h file from the system directory first, "" is to go to the user directory to find the. h file. A bit similar to Java in the ClassLoader, the default is the delegate load, you can also use the subclass-first way to load.

Creating Instances and Recycling

In the C language, declare a variable that can be used directly in the way it is declared or molloc.

In C + +, a new method is added, which is the same way as in Java.

Create

Release

Declaration (implicit): The object itself is created, not a pointer

Implicit release, no need to write code. Because the declared object is inside the stack, it is automatically released after the stack.

Molloc (Display): This method is used to allocate memory, the return value is a pointer

Use Free () to release

NEW: Allocate memory, return value is pointer

Use Delete to release

Molloc, new allocates memory, the return value is a pointer. and is allocated in the in-memory heap area and is not automatically freed, so you need to use free, delete to release.

In addition, after using FEEE, delete, it is best to set the value of the pointer to null, because free, delete only frees up the memory space occupied by the object, and the value of the pointer is still the first address of the object to occupy space before being released.

This is different from Java, where Java can be recycled automatically. object is set to null. The recycling mechanism in Java is to recycle an unreachable object using a generational recovery algorithm.

voidFun () {Menu* m1=NewMenu ();//explicitly declaring an objectMenu m2;//implicitly declaring an object     This->menulist->Push_back (M1);  This->menulist->push_back (&m2);}voidshowlist () {list<menu*>::iterator iter= This->menulist->begin ();  while(iter!= This->menulist->End ()) {Menu* menu=*ITER; cout<< m->tostring () <<Endl; ITER++; }}

This code, at compile time, is no problem, that is to say, in terms of writing, there is no error. However, a null pointer exception occurs when you execute Showlist (). The reasons are as follows:

In Fun (), the created M1 is not automatically released in the heap, the created M2 is automatically released in the stack, and the M2 object does not actually exist when the fun is executed. Then when the showlist () is executed, the variable to the M2 object is definitely empty, and the pointer to the M2 stored in the list has become a wild pointer.

3) namespace

namespaces, which are available in most languages. Their role is to differentiate.

Define namespaces

Namespace ns{

Your code

}

Import namespaces:

using namespace Std;

Use a namespace:

Std::xxxx

4) #define, typedef

TypeOf is an alias for an existing type. It is valid during the compile phase, because it is in the compile phase, so TypeDef has the function of type checking.

#define是宏定义, it happens in the preprocessing phase, which is just a simple and mechanical substitution of strings without any checking, until it is compiled. #define不只是可以为类型取别名, you can also define constants, variables, compile switches, and so on.

5) Operator overloading

When you learn C #, you know that you can reorganize an existing operator, that is, to give new functionality to the Operation method. But in C #, we seldom do this. Although there is no language-level support in Java, the + used for string concatenation in Java can actually be seen as an overloaded operator.

In the understanding of C + + operator overload, oh, this point, C # is a reference to C + + AH. In addition, structs are retained in C #. When it comes to structs, one more point, structs can be understood as classes in the C language.

A large number of operator overloads are used in C + +. Specifically, how to define operator overloading, use the time to say it.

A day and a half time, the understanding of things really not much, are the most basic. Although I also know that the string concatenation in C + + is not as arbitrary as Java and JavaScript. But these are not the difficult points, so I think there is no need to mention it.

Finally, a joke, Java programmer who does not understand JavaScript is not a good C + + programmer. JavaScript programmers who do not understand Java are not a good C + + programmer.

Java programmer learns the thoughts of a day and a half C + +

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.