A piece of code describes C ++ inheritance, polymorphism, youyuan, static variables, and overloading.

Source: Internet
Author: User

Class persion // abstract base class
{
Public:
Virtual void setdieage (int x) = 0; // pure virtual function
Protected:
PRIVATE:
};
Class man: Public persion
{
Friend class God; // usage of youyuan
PRIVATE:
Virtual void setdieage (int x) {m_dieage = x ;}
Protected:
PRIVATE:
Static int m_totalage; // static member
Int m_dieage;
};
 
Int man: m_totalage = 1000; // static member Initialization

Class wman: Public persion // inheritance
{
Friend class God;
PRIVATE:
Virtual void setdieage (int x) {m_dieage = x ;}
Protected:
PRIVATE:
Static int m_totalage;
Int m_dieage;
};

Int wman: m_totalage = 100; // the object of the class instance uses this copy.

Class God
{
Public:
Int tellyourdieage (MAN * P); // function overload
Int tellyourdieage (wman * P); // function overload
Void setyourdieage (persion * P, int X); // multi-State Processing abstract base class can process the derived class
Int tellyourtotalage (wman * P); // function overload
Int tellyourtotalage (MAN * P); // function overload
Protected:
PRIVATE:
};

Void God: setyourdieage (persion * P, int X) // Polymorphism
{
P-> setdieage (X );
}

Int God: tellyourdieage (MAN * P)
{
Return p-> m_dieage; // You can process private member variables.
}
Int God: tellyourdieage (wman * P)
{
Return p-> m_dieage;
}
Int God: tellyourtotalage (wman * P)
{
Return p-> m_totalage;
}
Int God: tellyourtotalage (MAN * P)
{
Return p-> m_totalage;

}

Man g_man, g_man1;
Wman g_wman;

God g_god;

Int _ tmain (INT argc, _ tchar * argv [])
{
G_god.setyourdieage (& g_man, 80 );
G_god.setyourdieage (& g_wman, 85 );

Printf ("% d \ n", g_god.tellyourdieage (& g_man ));
Printf ("% d \ n", g_god.tellyourtotalage (& g_man ));
Printf ("% d \ n", g_god.tellyourtotalage (& g_man1 ));

Sleep (5000 );
Return 0;
}

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.