首页 > 编程语言 > 详细

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

时间:2017-08-20 20:40:46      阅读:260      评论:0      收藏:0      [点我收藏+]
#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++指向类(非)静态成员的指针用法

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!