memb_pt.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // memb_pt.cpp -- dereferencing pointers to class members
  2. #include <iostream>
  3. using namespace std;
  4. class Example
  5. {
  6. private:
  7. int feet;
  8. int inches;
  9. public:
  10. Example();
  11. Example(int ft);
  12. ~Example();
  13. void show_in() const;
  14. void show_ft() const;
  15. void use_ptr() const;
  16. };
  17. Example::Example()
  18. {
  19. feet = 0;
  20. inches = 0;
  21. }
  22. Example::Example(int ft)
  23. {
  24. feet = ft;
  25. inches = 12 * feet;
  26. }
  27. Example::~Example()
  28. {
  29. }
  30. void Example::show_in() const
  31. {
  32. cout << inches << " inches\n";
  33. }
  34. void Example::show_ft() const
  35. {
  36. cout << feet << " feet\n";
  37. }
  38. void Example::use_ptr() const
  39. {
  40. Example yard(3);
  41. int Example::*pt;
  42. pt = &Example::inches;
  43. cout << "Set pt to &Example::inches:\n";
  44. cout << "this->pt: " << this->*pt << endl;
  45. cout << "yard.*pt: " << yard.*pt << endl;
  46. pt = &Example::feet;
  47. cout << "Set pt to &Example::feet:\n";
  48. cout << "this->pt: " << this->*pt << endl;
  49. cout << "yard.*pt: " << yard.*pt << endl;
  50. void (Example::*pf)() const;
  51. pf = &Example::show_in;
  52. cout << "Set pf to &Example::show_in:\n";
  53. cout << "Using (this->*pf)(): ";
  54. (this->*pf)();
  55. cout << "Using (yard.*pf)(): ";
  56. (yard.*pf)();
  57. }
  58. int main()
  59. {
  60. Example car(15);
  61. Example van(20);
  62. Example garage;
  63. cout << "car.use_ptr() output:\n";
  64. car.use_ptr();
  65. cout << "\nvan.use_ptr() output:\n";
  66. van.use_ptr();
  67. cin.get();
  68. return 0;
  69. }