C + + Learning notes 3--Some applications

Source: Internet
Author: User

Template
The general form of a function template definition:
Template < type form parameter table >
return type function name (formal parameter table) {    ...     function Body}

Example:
Define a function template for summation
Template <class type>type Sum (Type Xvar, type Yvar) {    return xvar + Yvar;}

After you define a function template, you need to call the function template in your program. The following code shows the invocation of the SUM function template.
int iRet = Sum (10, 20);
int dret = Sum (1.2, 3.45);
Eliminate the ambiguity of the template invocation and display the identity template type when the function template is called. Such as:
int iRet = Sum (10.5, 20);
Double Dret = sum<double> (10, 20.5);
Using a function template to generate an actual executable function is also called a template function.
Example: Using an array as a template parameter
#include <iostream>using namespace std;template <class type,int len>   //define a template type Max (type Array[len ]) {     //define function template    type RET = array[0];    for (int i=1;i<len;i++) {        ret = ret > array[i]? ret:array[i];    }    return ret;} int main (int argc,char* argv[]) {    int array[5] = {1,2,3,4,5};//define an integer array    int iret = max<int,5> (array);   Call function template Max    double dset[3] = {1.2, 3.45, 6.789};//define Real array    double Dret = max<double,3> (dset);  Calling function Templates Max    cout << dret << Endl;    return 0;}


Examples of overloaded function templates:
#include <iostream> #include <cstring>using namespace Std;template<class type>type Min (Type A, type B) {//define function template    return a < b? A:b;} char* Min (char* A, char* b) {//Reload function template    if (strcmp (A, B) < 0) return A;    return b;} int main (int argc, char* argv[]) {    cout << Min (3) << Endl;    cout << Min (' A ', ' B ') << Endl;    cout << Min ("Lasolmi", "Hello World") << Endl;    return 0;}

The definition of a class template:
template< type form Parameter table >
Class template Name
{
...//class template body
};
Class template member functions are defined as:
template< type form Parameter table >
return type class template name < type name table;:: member function name (formal argument list)
{
...//function body
}
The generated class is in the following form:
Class template name < type actual parameter table >
The newly generated class definition object is in the following form:
Class template name < type actual parameter table > object name
In a class template definition, a parameter in a type-formal parameter table can also be a different class template. For example:
Template<template<class a> class B>class CBase {private:    b<int> m_n;};


Class templates can also be inherited. For example:
T
Emplate<class t>class cderived:public t{public:    cdrived ();}; Template<class t>cderived<t>::cderived (): T () {    cout <<:: <<endl;} int main (int argc,char* argv[]) {    cderived<cbase1> D1;    return 0;}


Example: Simple class template
#include <iostream>using namespace Std;template<class T1, class T2>class MyTemplate {    T1 t1;    T2 t2;public:    MyTemplate (T1 tt1, T2 tt2) {t1 = tt1; t2 = tt2;}    void display () {cout << t1 << "<< T2 <<endl;}}; int main (int argc, char* argv[]) {    int a = 123;    Double b = 3.14159;    mytemplate<int,double> MT (A, b);    Mt.display ();    return 0;}


Default template parameters, for example:
Template<class T1, Class t2=int>
Provide default values for specific women's parameters, for example:
Template<class T1, class T2, int num=10>
Bounded array templates:
#icnlude <cassert>template<class T, int b>class Array {    t& operator[] (int sub) {        return sub > =0 && Sub < b;    };


Template customization: If you want to extend the functionality of the template's new class after defining the template, you need to overwrite the class template, which is the template class can


Enough to complete the function. The overwrite operation can target the entire class template, the partial class template, and the member functions of the class template. This overlay


Made to be customized.
For a template instance of the same type, its static data members are shared.
"STL Standard Template Library"
Sequence Container:
Vector class templates
Double-ended Queue class template
Linked List class template
Combined container
Set class template
Multiset class Templates
Map class Templates
Multimap class Templates
Algorithm
Non-modified sequence algorithm
Modified sequence algorithm
Sorting algorithms
Numerical algorithms
Iterators
Output iterators
Input iterators
Forward iterators
Bidirectional iterators
Random-Access iterators
"Rtti and Exception handling"
Run is type recognition (run-time type identification, RTTI) is a pointer to a base class or reference


Determines the type of an object.
Example: Both the Cbint class and the Cbstring class inherit from the CBase class, where there is a public method GetName () for the 3 classes, and Cbint


Class has its own unique method Getint (), Cbstring class has its own unique method GetString (). If you want to pass CBase


class, you must determine the specific class of the pointer when you call the Cbint class or the unique method of the Csstring class. Code completion for Word and face


Such a feature.
#include <cstdio>class CBase {   //base class public:    Virtual char * GetName () = 0;   Virtual method};class Cbint:public CBase {public:    char * GetName () {return "Cbint";}    int GetInt () {return 1;}}; Class Cbstring:public CBase {public:    char * GetName () {return "cbstring";}    char * GetString () {return "Hello";}}; int main (int argc, char* argv[]) {    cbase* B1 = (cbase*) new Cbint ();    printf (B1->getname ());    cbint* B2 = static_cast<cbint*> (B1);    Static substitution    if (B2) printf ("%d", B2->getint ());    cbase* C1 = (cbase*) new cbstring ();    printf (C1->getname ());    cbstring* C2 = static_cast<cbstring*> (C1);    if (C2) printf (c2->getstring ());    return 0;}


From the above code you can see that the base class CBase pointers B1 and C1 respectively point to the Cbint class and the Cbstring class object, and the


The program runtime base class is transformed by Static_cast, which creates a runtime type that is another process.
Rtti and references
#include <typeinfo>
typeID (P); P is a type of pointer
typeID () Gets a pointer to a base class type, not a subclass type or a derived class type, typeid () Gets a reference that is a subclass


Type.
"Rtti mapping Syntax"
dynamic_cast: A downward-pointing mapping for a security type.
For example, a downward transformation of a base class pointer is achieved through dynamic_cast.
Const_cast: Used to map constants and variables.
For example, modify the values of member variables and constants in the common method.
Static_cast: Maps for good behavior and better behavior, such as upward transformation and type auto-conversion.
For example, by static_cast, the child pointer is turned upward to a base-class pointer.
Reinterpret_cast: Used when mapping a type back to its original type.
For example, convert an integral type to a character type, and then the reinterpret_cast to the original type.
"Exception Handling"
Throw exception:
Example: An exception is thrown in the form of a class object with the error ID and error information.
#include <iostream> #include <cstring>using namespace Std;class ccustomerror {private:    int m_errorid;    Char m_error[255];p ublic:    ccustomerror (int errorid, char* Error) {        M_errorid = ErrorID;        strcpy (M_error, Error);    }    int Geterrorid () {return m_errorid;}    char* GetError () {return m_error;}}; int main (int argc, char* argv[]) {    try {        throw (new Ccustomerror (1, "exception appears!"));    catch (ccustomerror* error) {        //Output exception information        cout << "Exception ID:" << error->geterrorid () <<endl;        cout << "Exception info:" << error->geterror () << Endl;    }    return 0;}


Exception capture:
When an exception is thrown, it is destroyed once it is received by the exception handler. The exception handler should have an exception that accepts any


Ability. After the exception handler immediately follows the try block, the handled method is guided by the keyword catch.
Sometimes it is not always possible to include all of the exception types that may occur in the exception handling listed, so C + + provides the ability to handle any


The way to type exceptions is to add the "..." code in parentheses following the catch:
int main (int argc, char* argv[]) {    try {        throw ' string exception ';    } catch (ccustomerror* error) {        //Output exception information        cout << "Exception ID:" << error->geterrorid () <<endl;        cout << "Exception info:" << error->geterror () << Endl;    } catch (char* error) {        cout << exception Info: "<< error << Endl;    } catch (...) {        cout << "Unknown exception information" << Endl;    }    return 0;}


Exception match:
Can match to a base class, but not to its derived class.
In order to properly enter the specified exception handler, the derived class should be ranked in front of the exception handler, and the base


Class is at the back of the line.
Standard Exceptions:
Some of the standard exceptions provided by C + + are given below:
Namespace std{    //exception derived    class Logic_error;    Logic_error derived    class Domain_error;    Class Invalid_argument;    Class Length_error;    Class Out_of_range;    Class Bad_cast;    Class Bad_typeid;    Exception derived    class Runtime_error;    Runtime_errot derived    class Range_error;    Class Overflow_error;    Class Bad_alloc;}


"Program Debugging"
There are 4 common types of program errors: syntax errors, connection errors, run-time errors, and logic errors.



C + + Learning notes 3--Some applications

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.