C++-声明类的变量指针和函数指针

使用void(Student::*pwho) void = & Student::who // 构造函数指针

使用string Student::*p_name = & Student::m_name //构造变量指针

#include <iostream>
#include <cstdio>

using namespace std; 


class Student{
public:
    Student(const string& name):m_name(name){} 
    void who(void){
        cout << "学生的名字是" << m_name << endl; 
    }
    string m_name; 
}; 

int main() {
    //成员函数指针
    void(Student::*pwho)(void) = &Student::who; 
    //成员变量指针
    string Student::*p_name = &Student::m_name; 
    Student s("小明"); 
    //成员变量指针的调用 
    cout << s.*p_name << endl;
    //成员函数指针的调用
    (s.*pwho)(); // 用来定义指针变量
    Student* ps = new Student("小红"); 
     
    (ps->*pwho)(); 

    delete ps; 
    ps = NULL; 
}

猜你喜欢

转载自www.cnblogs.com/hyq-lst/p/12897924.html