#include <iostream> using namespace std; class Test { public: Test():x(0), y(0) { cnt++; } int x; int y; void print() const; static int cnt; static void print_s(); //静态成员函数不能够设置为const函数 ( cv qualifier??? ) }; int Test::cnt = 0; //静态成员变量的初始化 void Test::print_s() { cout<<cnt<<" object(s) has(have) been created"<<", visited by print_s function"<<endl; } void Test::print() const { cout<<"x = "<<x<<" y = "<<y<<endl; } int main() { int Test::*ptr; //声明指向类非静态成员变量的指针 void (Test::*print_p)() const; //声明指向类非静态成员函数的指针 print_p = &Test::print; //赋值 ptr = &Test::x; //赋值 Test a; a.*ptr = 1; //调用 (a.*print_p)(); //调用,前面的括号不能掉(运算符的优先级) int *ptr_1 = &Test::cnt; //声明和初始化指向类静态成员变量的指针 cout<<*ptr_1<<" object(s) has(have) been created"<<", visited by pointer"<<endl; //通过指针访问静态成员变量 Test::print_s(); //通过静态成员函数访问静态成员变量 return 0; }
时间: 2024-10-27 14:07:27