位置:首頁 > 高級語言 > C++教學 > 指向C++類

指向C++類

一個指向C++類作為一個指向的結構和訪問指針成員使用成員訪問運算符類 -> 操作符的方式完全相同,就像指針結構。在使用指針時,必須在使用前初始化指針。

讓我們試試下麵的例子來理解指針的概念類:

#include <iostream>
 
using namespace std;

class Box
{
   public:
      // Constructor definition
      Box(double l=2.0, double b=2.0, double h=2.0)
      {
         cout <<"Constructor called." << endl;
         length = l;
         breadth = b;
         height = h;
      }
      double Volume()
      {
         return length * breadth * height;
      }
   private:
      double length;     // Length of a box
      double breadth;    // Breadth of a box
      double height;     // Height of a box
};

int main(void)
{
   Box Box1(3.3, 1.2, 1.5);    // Declare box1
   Box Box2(8.5, 6.0, 2.0);    // Declare box2
   Box *ptrBox;                // Declare yiibaier to a class.

   // Save the address of first object
   ptrBox = &Box1;

   // Now try to access a member using member access operator
   cout << "Volume of Box1: " << ptrBox->Volume() << endl;

   // Save the address of first object
   ptrBox = &Box2;

   // Now try to access a member using member access operator
   cout << "Volume of Box2: " << ptrBox->Volume() << endl;
  
   return 0;
}

讓我們編譯和運行上麵的程序,這將產生以下結果:

Constructor called.
Constructor called.
Volume of Box1: 5.94
Volume of Box2: 102