C + + Notes

Source: Internet
Author: User
Tags data structures inheritance

The reference cannot be empty

Cannot define a reference that does not refer to anything

-int& r = NULL; Error

But "Wild references" or "dangling references" do exist.

-int & r = *new int (1);

++r;

cout<<r<<endl; 2

Delete &r;

++r; Not defined

The solution references a wild reference, just as the solution references a wild pointer, the results will be undefined, can cause crashes (segment errors), may accidentally modify data in other active heap memory, or nothing can happen and the results are correct, but no one can guarantee exactly what kind of result.

Reference cannot replace target

References can no longer refer to other objects once they are initialized

-int A = 10,b = 20;

int& c =a; C is the reference to a, and a is the target of C.

c = b; Assign the value of B to C to the target of a, rather than the C reference b

A reference has a "name" semantics only in its definition and initialization context, and once the definition and initialization have been completed, the reference, like the ordinary variable name, is given the "real" semantics, which represents its goal, not the alias itself.

Reference type parameter

The formal parameter of a function is an alias for an argument

A function's formal parameter can be declared as a reference form that is initialized by the corresponding position's arguments during parameter passing and becomes the alias of the argument

-void Fun (int& formal) {

cout<<&formal<< ":" <<formal<<endl;

}

-int actual = 10;

cout<< &actual<< ":" <<actual<<endl;

Fun (Actual);

Modifying an argument value in a function

. The value of the caller argument can be modified within the function body by reference parameter, which is the third way to output data externally from function to function, in addition to return values and pointer parameters.

-double rect (double w,double h,double* c,double& s) {

*c = (w+h) *2;

S=w*h;

return sqrt (w*w+h*h);

}

-double C,s,d=rect (4,3,&c,s);

cout<< "Diagonal Length:" << D <<endl;

cout<< "Perimeter of the rectangle:" << C <<endl;

cout<< "Rectangle's Area:" << s <<endl;

Avoid the overhead of object replication

Passing arguments by reference, the formal parameter is only an alias of the argument, not a replica, which avoids the copying of objects from the argument to the formal parameter, which is very useful for parameter types with complex data structures.

-struct user{

Char name[64];

Char address[256];

Char mbox[128];

}

-void Insert (user& User) {...}

-user User = {...};

Insert (user);

Prevent accidental modification of an argument

Even if the arguments passed are not constants, as long as the function does not need and should not make any modifications to the argument, the formal parameter that receives the argument can also be declared as a constant reference, which avoids the overhead of object duplication and raises a compilation error if an unexpected modification to the argument is made. Minimizing the risk of modifying an argument

-int sum (int const& x,int const& y) {

++x;//Error

y+=100;//Error

Rreturn X+y;

}

-int a=20,b=30,c=sum (A,B);

Receive constant type arguments

1. In C + +, all constants are with the right value attribute

2. Initialization of a target-writable left-value reference with a content-only right-valued object that is rejected by the compiler as an easy type

3. Constant-Reference formal parameters, because of their read-only constraints on the target, satisfy the principle that the compiler type is limited from tight to loose, and can accept the const argument

4.c++98 only the left value reference does not have a right value reference, so you can only refer to the right value with a normal left value reference can also refer to the normal or very left value, so the reference is also called a universal reference

-int Sun (int const& x,int const& y) {return x + y;}

-int a=20,b=30,c=sum (10,a-b);

Literal constant 10 is a pure right value, and the value of the a-b expression is the dead right value

Reference-Type return value

The local variable of a function has only a function or even a block or statement-level declaration cycle, and once the function returns, all local variables are immediately destroyed, even if the reference to them is obtained by the return value, and the target is undefined

-int& foo (void) {int n=123;return n;} Dangerous

int* bar (void) {int n=456;return &n;} Dangerous

int hum (void) {int n=789;return n;}

-int& foo (int& N) {return n;}

int& Bar (int* N) {return n;}

int& hum (int n) {return n;} Dangerous

-int* foo (int& N) {return &n;}

int* Bar (int* N) {return n;}

int* hum (int n) {return &n;} Dangerous

Returns the right value

1. The value form of the function return value naturally has the right value attribute, but from the function return value to pass the value to function pass the parameter, along with the object copy process

-int foo (void) {...}

Foo () = 1234; Error

2. To avoid the overhead of object duplication without losing the right value attribute as a function return value, you can return a constant-left reference to simulate or approximate the use effect of the right value

-int& foo (void) {...}

Foo () = 1234;

-int const& foo (void) {...}

Foo () = 1234; Error

Induction:

I. References

1. Definition: Reference is alias

2. Grammar:

Target type & Reference identifier = target variable

eg

int b;

int& a=b;

int &a = b;

int & A =b more forms

Constant reference: const int& c = b;

int const& c=b;

Char const* p;

Char *const p;

const char* p; Equivalent to char const* p;

3. References must be initialized at the time of definition.

4. You cannot define references that do not refer to anything, and you cannot initialize references with null

5. References cannot refer to other variables once they are defined

6. Reference-type function parameters:

1. Output data by reference parameter

2. Avoid the overhead of memory replication in the process of passing parameters by value by reference parameter

7. Reference-Type return value

1. Return the left value

2. Avoid the cost of memory duplication in the process of returning a value;

8. The difference between references and pointers

1. Pointers can be initialized with null

2. The pointer can change the target that the pointer points to, the reference cannot be

3. You can define a pointer to a pointer, but you cannot define a reference

&&-Illegal in c++98; C++11 is legal, but he does not represent a level two reference, but rather a reference to a right value

Why: Because the reference itself is not an entity, it is an alias that does not account for the address, so it cannot be referenced;

4. You can define a reference to a reference pointer, but you cannot define a pointer to a reference

int* p;

int*& r=p;

int A;

int& R=a;

ing &*p=&r; (x)

5. You can define an array of pointers, but you cannot define a reference array, but you can define an array reference;

int * P[5];

int & Ra[5]; Error

Array reference: Int (&ar) [5]=a;

Array pointers: Inti (*AP) [5]=&a;

9. The nature of the reference is the pointer! Reference or pointer implementation

Display Type conversions

Explicit type conversions for C language

int i;

Char c= (char) i;

void* pv= ...;

int* pi= (int*) PV;

There are four types of explicit type conversions in C + +

1. Static type conversions

static_cast< target type > (Source type Object)

The compiler does a compatibility check on the source type and the target type, checking that the error is not passed

The source type and the target type can do the static type conversion in two directions as long as implicit type conversions can be done in one direction.

If you convert a target type from a type of a source type to a constructor, or if the source type converts operator functions to the type of the target type, then the type conversion from the source type to the target type must be explicitly completed, and the static type conversion can be used for this occasion.

For example: int* pi=static_cast<int*> (PV);

2. Dynamic type Conversion

daynamic_cast< target type > (Source type Object)

The compiler first checks that the source type and target type are the same pointer or reference and that there is a polymorphic inheritance between the types, and there is no direct error

The compiler generates a command that executes at runtime to check whether the source and target types are consistent, inconsistent by returning null pointers or throwing an exception error

A conversion between a pointer or a reference that is commonly used in a parent-child class object that has a polymorphic inheritance relationship

3. Convert to Regular type

const_cast< target type > (Source type Object)

The compiler checks that the source type and target type are the same as pointers or references, and that the target type must be identical to each other except the normal property, otherwise the error is directly

To remove the const attribute on a pointer or reference

int const volatile X=100;

int const* p=&x;

*p=200; Error

int* q=const_cast<int*> (P);

*q=200;

4. Re-interpreting type conversions

reinterpret_cast< target type > (Source type Object)

The compiler checks to see if the source type and target type are pointers or references, or if one of the pointers is an integral type, otherwise the error is directly

Converting between pointers or references of any type means you can treat the same object as a different type and, in different ways, access or process

Whatever type of pointer is essentially the same as an integer, that is, a specially-byte sequence number in the address space

Induction:

Two. Explicit type conversions

1. Static type conversions

Static_cast: Reversal of an implicit type conversion. Custom type Conversions

2. Dynamic type Conversion

dynamic_cast: A parent-child class pointer or reference to polymorphic inheritance

3. Constant type Conversions

Const_cast: Removes the constant attribute of a pointer or reference

4. Re-interpreting type conversions

Reinterpret_cast: Different types of pointers or references, and transitions between pointers and integers

Classes and objects

A class is a user-defined conforming data type that includes the member variables of the expression property and also the member function of the expression behavior

Classes and structs

There is no intrinsic difference between class and structure in C + +, and the only difference is that

1. Class default access control property is private (private)

Class Dummy{int M_var;

Equivalent to:

struct Dummy{private:int M_var;

2. The default Access control property for the structure is common (public)

struct Dummmy{int M_var;

Equivalent to

Class Dummy{public:int M_var;

Related 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.