Pointer Reference-clever application in functions, Pointer Reference Function

Source: Internet
Author: User

Pointer Reference-clever application in functions, Pointer Reference Function


The previous article describes pointers and references. Also mentionedCannot define pointer pointing to reference(Because the reference is not an object and there is no actual address ). So can we define a pointer reference? The answer is yes, because the pointer itself is an object. You can define a reference to specify an object. Let's take a look at the usage of pointer reference:

 

Take the int type as an example:

Void ReferencePointer () {inti = 5; // variable iint * p = & I; // pointer p, pointing to variable iint * & pr = p; // pointer reference, point to the same variable icout <I <"" <* p <"" <* pr <endl; I = 10; cout <I <"" <* p <"" <* pr <endl; cout <"addr: "<p <" "<pr <endl; // the reference of the pointer is another alias of the pointer p, which has the same address pr = NULL as p; // Therefore, you can assign a null cout <"addr:" <p <"" <pr <endl;} to the pointer ;}

Result:

5 5 5

10 10 10

Addr: 0045FE50 0045FE50

Addr: 00000000 00000000

 

In a function, pointer reference can be used as a parameter.

 

Assume that there is a Book class. The basic definition is as follows:

Struct Book

{

String isbn;

String name;

Double price;

String author;

};


Now we need such a function: A file stores information about a Book (ISBN, Book name, and price). Now we want to read information from this file and assign it to The Book object.

 

To define such a function, we first think of an input (file path) and an output (Book object ). You may define the function as follows:

Book * GetBookFromFile (const string & filePath );

In this way, you must create a Book object in the function body (that is, to create a Book's memory space), but the memory space created in the function body is only valid within the function scope, in vitro, the function is invalid. That is to say, the returned Pointer Points to an arbitrary value, which is very dangerous.

 

For example, in the function:

 


After the function is called:

 

 

 

 

 

If this is not the case, you may think of another definition method as follows:

Book GetBookFromFile (const string & filePath );

Yes, this definition is acceptable, but a Book object needs to be declared in the function body. When the function returns a value, an object is copied. In this way, an object copy process is added to reduce the efficiency.

Book GetBookFromFile(const string& filePath){Book book;fstream fileInput(filePath);fileInput >> book.isbn >> book.name >> book.price;return book;}

 

 

 

 

 

You may also think of this method:

Void GetBookFromFile (Book & book, const string & filePath );

Yes, this does solve the problem above, and you do not need to copy the object any more. However, the new problem arises again. When the upper-layer calls this function, if you want to determine whether the returned book object has correctly obtained the file information, you must individually determine whether the base attribute is null. The following code. This will undoubtedly increase the upper-layer call burden.

Book;

GetBookFromFile (book, "E: \ book.txt ");

If (! Book. isbn. empty ()&&! Book. name. empty () & book. price> 0)

{

// To do...

}

Of course, there is an improved way to change the return value type void to bool, so that you can determine whether the function is successfully called by returning the bool value.

 

 

 

For the above problem, if the returned pointer is the Book pointer, you can directly determine whether the returned pointer is NULL. You can have the following two definitions:

Void GetBookFromFile (Book * book, const string & filePath );

Void GetBookFromFile (Book * & book, const string & filePath );

Of course, I recommend the second method, because the reference ensures that the passed pointer has a correct value (the reference must be initialized during definition)

 

Definition:

 

void GetBookFromFile(Book* pBook, const string& filePath){if (pBook == NULL){return;}fstream fileInput(filePath);fileInput >> pBook->isbn >> pBook->name >> pBook->price;}

void GetBookFromFile(Book*& pBook, const string& filePath){if (pBook == NULL){return;}fstream fileInput(filePath);fileInput >> pBook->isbn >> pBook->name >> pBook->price;}

 

The call methods for these two functions can be as follows:

Book* pBook = new Book();pBook->author = "SimileSunrise";GetBookFromFile(pBook, "E:\\book.txt");delete pBook;



 


Pointers are different from references in function calls.

"Int createbitree (Bitree & t)

Why cannot int createbitree (bitree * t) be used ??
"
Because the t defined in your main function is a pointer, if you use int createbitree (bitree * t) directly, it is equivalent to passing in the value. If you want to transmit the address, you need to use the second-level pointer:
Int createbitree (bitree ** t)

What is the difference between function reference and pointer in c ++?

# Include <stdio. h>

Void F (int a, int B) {printf ("hello % d \ n", a, B );};

Typedef void (& pF) (int, int );

Int main ()
{
Int a = 1, B = 3;
PF x = F;
X (a, B );
Printf ("0x % X 0x % X", F, x );
}

Global variables are stored in the Global static area of the memory. The global variables are always defined, because the compiler initializes their values to their default values and can define variables within the global scope, however, operations cannot be performed globally. Because operations are implemented in functions, You need to distinguish between initialization and assignment. For example, there is a global variable;

Int a; // equivalent to int a (int ());

The following operations on a are illegal:

++;
A --;
A + = 1;
....

The program is built by functions rather than files, so the above operations cannot be executed, so the compilation is different, in addition, the C/C ++ compiler seems to only recognize the declared definitions of variables within the global scope. So when you try global = 10, it thinks that you want to create a global variable without a type identifier, therefore, it gives you an error. In addition, it finds that the variable you are trying to Declare conflicts with the existing variable name, so it gives you an error...

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.