C + + Learning-Special class members

Source: Internet
Author: User

Static variables:

#include <iostream>#include<string>#include<typeinfo>using namespacestd;classa{ Public: A () {Total++; } Static intTotal ;};//@warn static member variables must be defined globallyintA::total =0; voidMain () {A A1;    A A2; cout<< a1.total<<Endl; cout<< a2.total<<Endl;
cout << a::total << Endl;}

Static member functions:

#include <iostream>#include<string>#include<typeinfo>using namespacestd;classa{ Public: A () {Total++; } Static voidShow () {cout<< Total <<Endl; }    voidEcho () {cout<< Total <<Endl; }Private:    Static intTotal ; intA;};intA::total =Ten; voidMain () {a::show ();    A A1; A1.echo ();

A a1,a2;
A1.echo ();
A1.show ();//You can also call a static function from an object


}

Static member functions and methods are still available after inheritance:

#include <iostream>#include<string>#include<typeinfo>using namespacestd;classa{ Public: A () {Total++; } Static voidShow () {cout<< Total <<Endl; }    voidEcho () {cout<< Total <<Endl; }Private:    Static intTotal ; intA;};classD | Publica{};intA::total =Ten; voidMain () {a::show (); B::show ();}

Static member functions cannot be described as virtual functions

Int (*fun) (int);//Declare a function pointer, the argument to the function is int, the return value is int
Int*fun (int);//Declare a function with a parameter of int and a return value of int type pointer

function pointers use:

#include <iostream>#include<string>#include<typeinfo>using namespacestd;intTest1 (intXinty) {    returnX +y;}intTest2 (intXinty) {    returnX *y;}voidMain () {int(*p) (int,int); P=test1; cout<< P (1,2) <<Endl; P=test2; cout<< P (1,2) <<Endl; }

Array of function pointers:

#include <iostream>#include<string>#include<typeinfo>using namespacestd;intTest1 (intXinty) {    returnX +y;}intTest2 (intXinty) {    returnX *y;}voidMain () {int(*p[2])(int,int) ={test1, test2}; cout<< p[0](1,2) <<Endl; cout<< p[1](2,3) <<Endl; }

C + + Learning-Special class members

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.