标签:
静态变量:
#include<iostream> #include<string> #include <typeinfo> using namespace std; class A{ public: A(){ total++; } static int total; }; //@warn 静态成员变量必须在全局进行定义 int A::total = 0; void main() { A a1; A a2; cout << a1.total<< endl; cout << a2.total<< endl;
cout << A::total << endl; }
静态成员函数:
#include<iostream> #include<string> #include <typeinfo> using namespace std; class A{ public: A(){ total++; } static void show() { cout << total << endl; } void echo() { cout << total << endl; } private: static int total; int a; }; int A::total = 10; void main() { A::show(); A a1; a1.echo();
A a1,a2;
a1.echo();
a1.show();//也可以通过对象调用静态函数
}
继承后静态成员函数和方法仍旧可用:
#include<iostream> #include<string> #include <typeinfo> using namespace std; class A{ public: A(){ total++; } static void show() { cout << total << endl; } void echo() { cout << total << endl; } private: static int total; int a; }; class B :public A{ }; int A::total = 10; void main() { A::show(); B::show(); }
静态成员函数不能说明为虚函数
int(*fun)(int);//声明一个函数指针,指向的函数的参数为int,返回值为int
int*fun(int);//声明一个函数,函数的参数为int,返回值为int型指针
函数指针使用:
#include<iostream> #include<string> #include <typeinfo> using namespace std; int test1(int x,int y){ return x + y; } int test2(int x, int y){ return x * y; } void main() { int(*p)(int, int); p = test1; cout << p(1, 2)<< endl; p = test2; cout << p(1, 2) << endl; }
函数指针数组:
#include<iostream> #include<string> #include <typeinfo> using namespace std; int test1(int x,int y){ return x + y; } int test2(int x, int y){ return x * y; } void main() { int(*p[2])(int, int) = { test1, test2 }; cout << p[0](1,2) << endl; cout << p[1](2, 3) << endl; }
标签:
原文地址:http://www.cnblogs.com/siqi/p/4641249.html