C++的指针

  • C++可以定义-成员指针变量-(指向成员的指针,而不是指针型成员)
  • 成员指针变量保存的是成员在结构体中的相对地址
  • 成员指针的定义:
    • int Student::*mp = &Student::age;
  • 成员指针的调用:
    • st.*mp = 18;
  • 示例: ```cpp

    include

    include

    using namespace std;

struct Student{ int number; bool gender; int age; };

int main(int argc, char const *argv[]) { struct Student st = {1907201, 1, 18}; cout << st.number << endl;

  1. int *p1 = &st.number;
  2. bool *p2 = &st.gender;
  3. int *p3 = &st.age;
  4. cout << p1 << endl;
  5. cout << p2 << endl;
  6. cout << p3 << endl;
  7. cout << "age : " << *p3 << endl;
  8. cout << "成员指针变量" << endl;
  9. int Student::*mp1 = &Student::number;
  10. bool Student::*mp2 = &Student::gender;
  11. int Student::*mp3 = &Student::age;
  12. printf("%p\n", mp1);
  13. printf("%p\n", mp2);
  14. printf("%p\n", mp3);
  15. cout << "age : " << st.*mp3 << endl;
  16. return 0;

} ```