C ++ Primer study note _ 101 _ special tools and technology, primer_101

Source: Internet
Author: User

C ++ Primer study note _ 101 _ special tools and technology, primer_101
Special tools and technologies-runtime type recognition



Reference:

The following two operators provide RTTI:

1.TypeidReturns the actual type of the pointer or referenced object.

2.Dynamic_castTo safely convert a pointer or reference of a base class to a pointer or reference of a derived type.

For classes with virtual functionsRuntimeExecute the RTTI operator, but for other types, calculate the RTTI operator during compilation.

When you have a base class reference or pointer but need to execute a derived class operation that is not part of the base class, you need to dynamically force type conversion. Generally, the best way to obtain a derived class from a base class pointer is to use a virtual function. When a virtual function is used, the compiler automatically selects the correct function based on the actual type of the object.

However, in some cases, virtual functions cannot be used. In these cases, RTTI provides an optional mechanism. However, this mechanism is more error-prone than using virtual functions:The programmer must know which type the object should be forcibly converted,Check whether the conversion is successful..



I,Dynamic_castOperator

You can use the dynamic_cast operator to convert the reference or pointer of a base class object to a reference or pointer of another type in the same inheritance level. The pointer used with dynamic_cast must be valid -- it must be 0 or point to an object.

Unlike other forced conversions,Dynamic_castInvolved runtime type check. If the object bound to the reference or pointer is not of the target type, dynamic_cast fails. If the conversion to dynamic_cast of the pointer type fails, the result of dynamic_cast is 0. If the conversion to dynamic_cast of the reference type fails, a bad_cast type exception is thrown.

1. Use the dynamic_cast Operator

    if (Derived *derivedPtr = dynamic_cast<Derived *>(basePtr))    {        //...    }    else    {        //...    }

Explanation: At runtime, if basePtr actually points to the Derived object, the conversion is successful, and the derivedPtr is initialized to the Derived object pointed to by basePtr; otherwise, the conversion result is 0, this means that the derivedPtr is set to 0 and the condition in if fails. You can also apply dynamic_cast to a pointer with a value of 0. The result is 0.

[Best practices]

 Execute in conditionsDynamic_castThis ensures that the conversion and the conversion result are tested in an expression!



2. Use dynamic_cast and reference type

Form:

    dynamic_cast<Type &>(val);

Only when val actually references a Type object or if val is a Type-derived object can the dynamic_cast operation convert the operand val to Type & Type.

Because there is no null referenceIt is impossible to use the check policy for pointer forced type conversion for reference.On the contrary, when the conversion fails, it throws a std: bad_cast exception, which is defined in the typeinfo header file of the library.

void f(const Base &b){    try    {        const Derived &d = dynamic_cast<Derived &>(b);    }    catch(std::bad_cast)    {    }}

// P648 exercise 18.13-15 // 1) class A {public: virtual void func () {}}; class B: public A {}; class C: public B {}; class D: public B, public A {}; int main () {C c; A * pa = & c; if (C * pc = dynamic_cast <C *> (pa) {cout <"dynamic_cast success" <endl ;} else {cout <"dynamic_cast fail" <endl ;}}

//2)    try    {        C &temp = dynamic_cast<C &>(*pa);    }    catch(std::bad_cast &e)    {        cout << e.what() << endl;    }

// 18.16 when can I use dynamic_cast to replace virtual functions?/** A: * When we need to add a function to a derived class, however, you cannot use dynamic_cast to replace the virtual function */



II,TypeidOperator

The typeid operator allows the program to ask an expression: What type are you?

  typeid(e) 

If the expression type isClass and the class contains one or more virtual functions, The dynamic type of the expression may beDifferent fromIts static compilation type. For example, if an expression is used to unreference a base class pointer, the type of the expression during static compilation is the base class type. However, if the pointer actually points to a derived class object, the typeid operator indicates that the expression type is a derived type.

The typeid operator can be used with any type of expression. Built-in expressions and constants can be used as the operands of the typeid operator. If the operand is not a class type or a class without a virtual function, the typeid operator specifies the static type of the operand. If the operand is a class type that defines at least one virtual function, the computing type at runtime.

The result of the typeid operator is an object reference of the standard library type named type_info. To use the type_info class, you must include the library header file typeinfo.


UseTypeidOperator

The most common purpose of typeid is to compare the types of two expressions, or compare the types of expressions with specific types:

    Base *pb;    Derived *pd;    if (typeid(*pb) == typeid(*pd))    {        cout << "typeid(*pb) = typeid(*pd)" << endl;    }    if (typeid(pb) == typeid(pd))    {        cout << "typeid(pb) = typeid(pd)" << endl;    }    if (typeid(*pb) == typeid(Derived))    {        cout << "typeid(*pb) = typeid(Base)" << endl;    }    int a;    if (typeid(int) == typeid(a))    {        cout << "typeid(int) = typeid(a)" << endl;    }

[Careful mine]

Dynamic type information is returned only when the operand of typeid is a class object with a virtual function. The test pointer (equivalent to the object pointed to by the pointer) returns the static and compile-time type of the pointer.

    Derived d;    Base *pb = &d;    if (typeid(*pb) == typeid(Derived))    {        cout << "typeid(*pb) = typeid(Base)" << endl;    }


If the pointer pb value is 0, if the pb type is a type with a virtual function, typeid (* p) throws a bad_typeid exception; if no virtual function is defined for the p type, the result is irrelevant to the p value.


// P650 exercise 18.17 AndQuery a; Query_base * qb1 = & a, * qb2; if (dynamic_cast <AndQuery *> (qb1) cout <"success" <endl; else cout <"failure" <endl; if (dynamic_cast <AndQuery *> (qb2) cout <"success" <endl; else cout <"failure" <endl;

// Exercise 18.18 try {dynamic_cast <AndQuery &> (* qb1); cout <"success" <endl;} catch (std: bad_cast) {cout <"failure" <endl;} try {dynamic_cast <AndQuery &> (* qb2); cout <"success" <endl;} catch (std :: bad_cast) {cout <"failure" <endl ;}

// Exercise 18.19 AndQuery a; Query_base * qb1 = & a, * qb2; try {dynamic_cast <AndQuery &> (* qb1); if (typeid (* qb1) = typeid (AndQuery) {cout <"Same" <endl;} else {cout <"Not Same" <endl ;}} catch (std :: bad_cast) {cout <"failure" <endl;} if (typeid (* qb1) = typeid (* qb2 )) {cout <"Same" <endl;} else {cout <"Not Same" <endl ;}


After learning c primer plus, what should I learn?

I have read a lot of books from the author. The advantage is that the knowledge is wide and the disadvantage is that it is easy to be refined. I personally strongly suggest:
Clear goals-clear programming language-select a good book for good reading, good programming (manual programming is the focus)-select a lot of books (the same programming language) as a tool book-start to achieve the goal

In addition, if you only want to practice applications (such as Enterprise Portal and office platform websites), Learning data structures is of little use. The application algorithm has already been saved to the relevant class library. If you are not interested in it (Love coding algorithm, curious ...), The help is really not too great.
Assembly language .. First, it is not practical for window design .. It is hard to understand and use. If you do not want to do embedded-related things, you really don't need it. If you are really interested, the current compilers all come with disassembly, you can have a look at it.

As an enterprise portal and an Office Platform website, php, mysql, and HTML must be used. You can use dreamweaver, wamp, and other environments, I used "elaborate on php" when I first studied it. As for HTML, there are entry-level documents everywhere on the Internet, which are basically used for the interface of the artist. dreamweaver is very simple.

Besides php, java is also a good choice. Although I don't know it, java is still very powerful in website maintenance and so on. I don't know it, but I can only make one proposal.

I want to learn C language recently. Is there a little foundation? Can I recommend this book? How can I see a book called c primer plus on the Internet?

This book describes the concepts and knowledge of C language programming.
The book consists of 17 chapters. Chapter 1 and Chapter 2 learn the preparatory knowledge required for C programming. Chapter 5 to 15 describes the knowledge of C language, including data type, formatting input and output, operators, expressions, process control statements, functions, arrays and pointers, string operations, memory management, bit operations, and so on. The knowledge is applicable to C99 standards; in addition, Chapter 10th strengthens the discussion of pointers, and Chapter 12th introduces the concept of dynamic memory allocation, which is more suitable for readers. Chapter 2 and Chapter 2 discuss C Preprocessor, C library functions, and advanced data representation (data structure. The appendix provides the answers to the exercises and programming exercises and a wide range of C Programming references.
This book is suitable for readers who want to systematically learn the C language and programmers who are proficient in other programming languages and want to further master and consolidate the C programming technology.

Directory
[1] Chapter 1 Overview
1.1 C Language Origin
1.2 reasons for using C language
1.3 C Language Development Direction
1.4 basic principles of computer work
1.5 advanced computer language and Compiler
1.6 seven steps for using C language
1.7 Programming Mechanism
1.8 language standards
Organizational structure of the 1.9 book
1.10 books
1.11 conclusion
1.12 exercise Review
1.13 programming exercises
Chapter 2 C language Overview
2.1 A simple example of C Language
2.2 instance description
2.3 structure of a simple program
2.4 skills for making programs readable
2.5 go further
More than 2.6 Functions
2.7 debugging
2.8 keywords and reserved identifiers
2.9 key concepts
2.10 conclusion
2.11 exercise Review
2.12 programming exercises
Chapter 2 data and C
3.1 sample program
3.2 variables and constant data
3.3 Data: Data Type keywords
3.4 C Data Type
3.5 Use Data Types
3.6 parameters and vulnerable errors
3.7 another example: Escape Sequence
3.8 key concepts
3.9 conclusion
3.10 exercise Review
3.11 programming exercises
Chapter 2 string and formatting input/output
4.1 leading Program
4.2 string Introduction
4.3 constants and C preprocessors
4.4 research and utilization of printf () and scanf ()
4.5 key concepts
4.6 conclusion
4.7 exercise Review
4.8 programming exercises
Chapter 4 Operators, expressions, and statements
5.1 loop Introduction
5.2 Basic Operators
5.3 Other operators
5.4 expressions and statements
5.5 type conversion
5.6 functions with Parameters
5.7 A sample program
5.8 key concepts
5.9 conclusion
5.10 exercise Review
5.11 programming exercises
Chapter 3 C control statement: loop
6.1 explore the while LOOP
6.2 while statement
6.4 uncertain cycle and counting cycle
6.5 for Loop
6.6 more assignment operators: + =,-=, * =,/=, and % =
6.7 comma Operator
6.8 exit condition loop: do while
6.9 select the loop
6.10 nested loop
Array 6.11
6.12 example of a loop using function return values
6.13 key concepts
6.14 conclusion
6.15 exercise Review
6.16 programming exercises
Chapter 3 C control statements: branch and jump
7.1 if statement
7.2 Add the else keyword to the if statement
7.3 obtain Logic
7.4 a program for counting words
7.5 conditional operators? :
7.6 cycle auxiliary means: continue and break
7.7 multiple options: switch and break
7.8 goto statement
7.9 key concepts
7.10 conclusion
7.11 exercise Review
7.12 programming exercises
Chapter 2 character input/output and input confirmation
8.1 single character I/O: getchar () and putchar ()
8.2 buffer zone
8.3 terminate keyboard input
8.5 create a user-friendly interface
8.6 input confirmation
8.7 menu browsing
8.8 key concepts
8.9 Conclusion
8.10 exercise Review
8. 1 ...... remaining full text>

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.