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;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM