码迷,mamicode.com
首页 > 编程语言 > 详细

c++指向类(非)静态成员的指针用法

时间:2017-08-20 21:13:28      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:访问   clu   static   visit   point   静态成员   space   静态   logs   

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

 

c++指向类(非)静态成员的指针用法

标签:访问   clu   static   visit   point   静态成员   space   静态   logs   

原文地址:http://www.cnblogs.com/rocklee25/p/7401158.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!