C++ 指向类的指针


一个指向 C++ 类的指针与指向结构的指针类似,访问指向类的指针的成员,需要使用成员访问运算符 ->,就像访问指向结构的指针一样。与所有的指针一样,您必须在使用指针之前,对指针进行初始化。

下面的实例有助于更好地理解指向类的指针的概念:

  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class Box
  5. {
  6. public:
  7. // 构造函数定义
  8. Box(double l=2.0, double b=2.0, double h=2.0)
  9. {
  10. cout <<"Constructor called." << endl;
  11. length = l;
  12. breadth = b;
  13. height = h;
  14. }
  15. double Volume()
  16. {
  17. return length * breadth * height;
  18. }
  19. private:
  20. double length; // Length of a box
  21. double breadth; // Breadth of a box
  22. double height; // Height of a box
  23. };
  24.  
  25. int main(void)
  26. {
  27. Box Box1(3.3, 1.2, 1.5); // Declare box1
  28. Box Box2(8.5, 6.0, 2.0); // Declare box2
  29. Box *ptrBox; // Declare pointer to a class.
  30.  
  31. // 保存第一个对象的地址
  32. ptrBox = &Box1;
  33.  
  34. // 现在尝试使用成员访问运算符来访问成员
  35. cout << "Volume of Box1: " << ptrBox->Volume() << endl;
  36.  
  37. // 保存第二个对象的地址
  38. ptrBox = &Box2;
  39.  
  40. // 现在尝试使用成员访问运算符来访问成员
  41. cout << "Volume of Box2: " << ptrBox->Volume() << endl;
  42. return 0;
  43. }

当上面的代码被编译和执行时,它会产生下列结果:

  1. Constructor called.
  2. Constructor called.
  3. Volume of Box1: 5.94
  4. Volume of Box2: 102