zoukankan      html  css  js  c++  java
  • c++指向类(非)静态成员的指针用法

    #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函数 ( static member function cannot have cv qualifier??? cv 限定符 即 const and volatile)
    };
    
    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;
    }
  • 相关阅读:
    noip模拟赛#38
    noip模拟赛#45
    noip模拟赛#15
    noip模拟赛#14
    noip模拟赛
    rp++
    bzoj2127: happiness
    bzoj3209:3209: 花神的数论题
    10.1 plan
    FFT
  • 原文地址:https://www.cnblogs.com/rocklee25/p/7401158.html
Copyright © 2011-2022 走看看