C + + Learning Note 2--Object-oriented

Source: Internet
Author: User
Tags define abstract

Declaration format for the class:
Class class name identifier {[public:][data member Declaration] [Declaration of member function][private:][data member declaration] [Declaration of member function][protected:][declaration of data member] [Declaration of member function]};

"Implementation of the Class"
The first method is to define the members of the class in the class body.
The second method can also place the implementation of member functions within the class body outside the class body, but if the class member is defined outside the class body, the domain operator "::" is used, and the effect is the same in the body and outside the class body.
The C + + language can implement the declaration of functions and the definition of functions placed in different files, generally in the header file into the function of the Declaration, the implementation of the file into the implementation of the function. You can place the definition of a class in the header file and place the class member variable inside the implementation file.
"Constructors"
How to construct a class:
Class CPerson {public:    CPerson ();    int m_iindex;    int GetIndex ();};/ /constructor Cperson::cperson () {    m_iindex = 10;}


CPerson () is the default constructor for CPerson, and the constructor method can be defined as a parameter.
"Copy Constructor"
The copy constructor is the argument to the function that is an already initialized class object.
Example:
#include <iostream> #include <cstring>using namespace Std;class person {public: person    (int _index, Char *_name); Constructor    (person & Copyperson);//copy constructor    int index;    Char name[30];};/ /constructor Person::P Erson (int _index, char *_name) {    index = _index;    strcpy (name, _name);} Copy constructor Person::P Erson (Person & Copyperson) {    index = Copyperson.index;    strcpy (name, copyperson.name);} int main (int argc, char *argv[]) {person    P (1, "Lasolmi");    Person Q (p);    cout << q.name << Endl;    return 0;}


"Destructor"
Constructors are primarily used to assign values to some data members in an object when the object is created, primarily to initialize the object.
The function of a destructor is to release an object, and use it to do some cleanup work before the object is deleted, which is the opposite of the function of the constructor.
Cperson::~cperson () {    delete[] m_pmessage;}


"Class Member"
The members of the public property are visible externally and are visible internally.
The members of the private attribute are not visible externally and are visible internally.
The members of the protected property are not visible to the outside, are visible internally, and are visible to derived classes.
By default, the properties of a class member are private.
"Inline member function"
Intra-class (default inline within class) declaration: Inline char* GetUserName () const;
Out of Class Direct definition: inline char* cuser::getusername () const {...}
"Static class member"
Static class members are identified with the static keyword before the class member definition. For example:
Class Cbook {public:    static unsigned int m_price;}; When you define a static data member, you typically need to initialize the static member outside the class body. For example: unsigned int cbook::m_price = 10; For static members, access to the class name can be accessed not only through object access, but also directly. For example: int main (int argc,char* argv[]) {    Cbook book;    cout << cbook::m_price << Endl; Access static members by class name    cout << book.m_price << Endl;//Access static members by object    return 0;}


A static data member can be the type of the current class, while other data members are only pointers or reference types for the current class.
Cases:
Class Cbook {public:    static unsigned int m_price;    Cbook M_book;           An illegal definition that does not allow the definition of an object of the owning class in the class    static Cbook M_vcbook;  correctly, static data members allow defining the class object to which the class belongs    Cbook *m_pbook;         Correct, allows you to define a pointer type object of the owning type of the class}


A static data member can be the default parameter for a member function.
A part of a static member function is written outside the class without adding static.
This pointer is hidden in the C + + class.
"Nested Class"
Example: When defining a CList class, a nested class Cnode is defined internally.
#include <iostream> #include <cstring>using namespace std; #define MaxLen 128class CList {public:    class CNode {        friend class CList;    Private:        int m_tag;    Public:        Char M_name[maxlen];    }; Public:    CNode M_node;    void Setnodename (const char *pchdata) {        if (pchdata! = NULL) {            strcpy (m_node.m_name, pchdata);}    }    void Setnodetag (int tag) {        M_node.m_tag = tag;    }}; int main (int argc, char* argv[]) {    CList C;    C.setnodename ("Lasolmi");    cout << c.m_node.m_name << Endl;    return 0;}


The code above defines a private member M_tag in the nested class Cnode, defines a public member M_name, which, for the perimeter class CList, usually cannot access the private members of the nested class, although the nested class is defined internally. However, the code above defines the CList class as its friend class when defining the Cnode class, which enables the CList class to access private members of the Cnode class.
For internal nested classes, it is only allowed to be used in the perimeter class domain, which is not visible in other class domains or scopes.
You can invoke the following methods:
Clist::cnode node;
Local class: The definition of a class is placed in a function.
"Friend" friend
Friend class:
Class B {public:    friend class A;    ...}

Friend Method:
Class B {    friend void a::function ();    ...};

For the original function, not only can it be a member function of a class, but it can also be a global function.
Class B {    friend void function ();    ...} void function () {...}

"Namespaces"
The namespace is defined in the following format:
Namespace name {    constants, variables, functions, etc.}

The general form of a reference space member is:
Namespace name:: member;
Example: Defining a Namespace
#include <iostream>using namespace Std;namespace MyName1 {//define namespace    int ivalue = 10;} namespace MyName2 {//define namespace    int ivalue = 20;} int ivalue = 30; global variable int main (int argc,char* argv[]) {    cout << myname1::ivalue << Endl;//reference MyName1 namespace variables    cout & lt;< Myname2::ivalue << Endl; Referencing variables in the MyName2 namespace    cout << ivalue << Endl;    return 0;}

Another way to reference a member in a namespace is to use the using namespace statement. The general form is:
using namespace namespace name;
If you use the using namespace statement, you can use it directly when you reference a member in the space.
Example: Define a nested namespace.
#include <iostream>using namespace std;namespace output {    void Show () {        cout << "Output ' s function!" << Endl;    }    namespace MyName {        void Demo () {            cout << "MyName ' s function!" << Endl;        }}    } int main (int argc, char* argv[]) {    output::show ();    Output::myname::D emo ();    return 0;}

Inheritance
Class inheritance is in the following form:
Class Derived classes name identifier: [Inheritance Method] base class name identifier {    [access control modifier:]    [member declaration list]}

There are 3 derived types of inheritance: Public,protected,private.
Public (common derivation): A common derivation represents a public data member and a member function in the base class, still public in a derived class, and private in a derived class for private data members and member functions in a class.
Private (privately derived): A private derivation represents a public, protected data member, and member function in the base class that can be accessed in a derived class. Private data members in a base class that are not accessible in derived classes.
protected (protected derivation): Protected derivation represents the public, protected data members, and member functions in the base class, which are protected in derived classes. The protected type can be accessed when the derived class is defined, and objects declared with derived classes are not accessible, that is, outside the class body. Protected members can be used by all derived classes of the base class. This property can propagate infinitely downward along the inheritance tree.
"Subclasses hide member functions of the parent class"
The Class B is a derived class of Class A, there is a method function () in a, and a method function () in B, then Class B member B uses its own function () method to:
B.function ();
Subclasses use the parent class function () method to:
B.a::function ();
"Overloaded operator"
Declaration form for overloaded operators:
operator type name ();
Overloaded operators are not allowed: ".", "*", "::", "?", ":".
Example: Summing with overloaded operators
#include <iostream>using namespace Std;class cbook {public:    cbook (int ipage) {        m_ipage = ipage;    }    Cbook operator+ (Cbook b) {        return Cbook (m_ipage+b.m_ipage);    }    void display () {        cout << m_ipage <<endl;    } Protected:    int m_ipage;}; int main (int argc,char* argv[]) {    Cbook BK1 (ten);    Cbook BK2 ();    Cbook tmp (0);    TMP = BK1 + BK2;    Tmp.display ();    return 0;}

"Multiple Inheritance"
C + + supports multiple inheritance. Multiple inheritance refers to multiple base class name identifiers, which are declared as follows:
Class Derived classes name identifier: [Inheritance Method] base class name identifier 1,..., access control adornment's baseline class name identifier n{    [access control modifier:]    [member declaration list]};

Example: Birds can fly in the sky, and can swim in the water, and waterfowl can fly in the sky, but also can swim in the water. So when you define water birds, you can use both birds and fish as their base classes.
#include <iostream>using namespace Std;class cbird {public:    void Flyinsky () {        cout << "Birds can fly in the sky" << Endl;    }    void Breath () {        cout << "Bird can Breathe" << Endl;    }; Class Cfish {public:    void Swiminwater () {        cout << "fish can swim in water" << Endl;    }    void Breath () {        cout << "Fish can Breathe" << Endl;    }; Class Cwaterbird:public Cbird, public cfish {public:    void Action () {        cout << "waterfowl can fly and swim" << endl;
   }};int Main (int argc, char* argv[]) {    Cwaterbird waterbird;    Waterbird. Flyinsky ();    Waterbird. Swiminwater ();    return 0;}

When you need to use the breath () method, you can do this:
Waterbird. Cfish::breath (); Call the breath member function of the Cfish class
Waterbird. Cbird::breath (); The number of breath member functions that call the Cbird class
Ambiguity: When two or more parent classes of a derived class contain function functions, the derived class will not know which function member functions to invoke, which results in two semantics.
The order in which multiple inherited constructors are called is based on the order of life in the class-derived table. Derived tables are the same as those inherited in multiple inheritance definitions, in the order in which they are called in the sequence of the base class name identifiers.
"Polymorphic"
In the C + + language, polymorphic means: functions with different functions can use the same function name.
Polymorphism is achieved through the use of a binder. A link is a process in which a computer program is associated with one another.
The series is divided into: static and dynamic, according to the stages of the process.
In C + +, there are two types of polymorphism: function overloading and virtual functions, depending on the time of the binder.
Declare member functions as virtual functions in the base class using virtual.
The difference between overrides and overloads is that overloading is the same as the function name of the same hierarchy, and overrides are identical to the function prototypes of the member functions in the inheritance hierarchy.
Example: Using virtual function to implement dynamic binding
#include <iostream> #include <cstring>using namespace Std;class cemployee {   //define CEmployee class public:    int m_id;    Char m_name[128];    Char m_depart[128];    CEmployee () {        memset (m_name, 0, +);        memset (M_depart, 0, +);    }    virtual void Outputname () {     ///define a virtual member function        cout << "Employee Name:" << m_name << Endl;    }}; Class Coperator:public CEmployee {  //derive a subclass from the CEmployee class public:    char m_password[128];    void Outputname () {        cout << operator Name: "<< m_name << Endl;    }}; int main (int argc, char* argv[]) {    CEmployee *pworker = new Coperator ();//define CEmployee type pointer, call Coperator class constructor    strcpy (Pworker->m_name, "Lasolmi");   Set M_name data member information    pworker->outputname ();                Call the Outputname member function of the Coperator class    delete pworker;                       Release object    return 0;}

Virtual functions are limited in the following ways:
(1) Only the member function of a class can be a virtual function.
(2) A static member function cannot be a virtual function because a static member function is not restricted to an object.
(3) An inline function cannot be a virtual function, because an inline function cannot dynamically determine its position in the run.
(4) Constructors cannot make virtual functions, destructors are usually virtual functions.
When deriving a subclass Cwaterbird class from the Cbird class and the Cfish class, there will be two canimal classes in the Cwaterbird class. So how do you derive the Cwaterbird class so that it only has one canimal base class? The C + + language provides the Xu inheritance mechanism, solves this problem.
Example: Virtual inheritance
#include <iostream>using namespace Std;class canimal {//define an animal public:    canimal () {cout<< "animal-like structure" < <endl;}    void Move () {cout<< "Animals can move" <<endl;}}; Class Cbird:virtual public Canimal {//From Canimal class virtual inheritance Cbird class public: Cbird    () {cout<< "birds are constructed" <<ENDL;}    void Flyinsky () {cout<< "birds can fly in the sky" <<ENDL;    void Breath () {cout<< "Bird Can Breathe" <<endl;}}; Class Cfish:virtual public Canimal {//From Canimal class virtual inheritance Cfish class public: Cfish    () {cout<< "Fish is constructed" <<ENDL;}    void Swiminwater () {cout<< "fish can swim in the water" <<ENDL;    void Breath () {cout<< "with the ability to swim in the water" <<endl;}}; Class Cwaterbird:public Cbird,public cfish {public:    Cwaterbird () {cout<< "water birds are constructed" <<ENDL;}    void Action () {cout<< "waterfowl can fly and swim" <<endl;}}; int main (int argc,char* argv[]) {    Cwaterbird waterbird;    return 0;}

The output is:
Animal classes are constructed
Birds are constructed
Fish are constructed
Water birds are constructed
"Abstract class"
A class that contains at least one pure virtual function is called an abstract class.
An abstract class can only be used as a base class to derive new subclasses, not to instantiate in a program (that is, an object that cannot describe an abstract class), but a pointer to an abstract class may be used.
Pure vitual function: Refers to a virtual member function that is marked as not specifically implemented, and does not have function functions.
Virtual functions cannot be called directly, but only provide an interface that is consistent with the derived class.
Declares a virtual function in the form of:
Virtual type function name (parameter table column) = 0;
Implement member functions in an abstract class: Abstract classes are typically used as the parent class for other classes, and subclasses derived from abstract classes, if they are abstract classes, must implement all pure virtual functions in the parent class.
Example: Implementing a member function in an abstract class
#include <iostream> #include <cstring>using namespace Std;class cemployee {//define CEmployee class Public:int m_id;    Char m_name[128];    Char m_depart[128]; virtual void outputname () = 0;    Define abstract member functions};class coperator:public cemployee {Public:char m_password[128];    void Outputname () {cout<< "operator name:" &LT;&LT;M_NAME&LT;&LT;ENDL;} Coperator () {strcpy (M_name, "Lasolmi");}};    Class Csystemmanager:public CEmployee {//define Csystemmanager class Public:char m_password[128];    void Outputname () {cout<< "system administrator Name:" &LT;&LT;M_NAME&LT;&LT;ENDL;} Csystemmanager () {strcpy (M_name, "Congli");}};         int main (int argc, char* argv[]) {CEmployee *pworker;  Defines the CEmployee type pointer pworker = new Coperator ();      Call the constructor of the Coperator class to assign a value of Pworker->outputname () to Pworker;             Call the Outputname member function of the Coperator class delete pworker;             Release Pworker Object pworker = NULL;  Set the Pworker object to null Pworker = new Csystemmanager (); The Csystemmanager uses the constructor of the class to assign a value to the Pworker pworker-> Outputname ();             Call the Outputname member function of the Csystenmanager class delete pworker;             Release Pworker Object pworker = NULL; Set the Pworker object to null return 0;}


C + + Learning Note 2--Object-oriented

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.