C++ クラスへのポインタ

C++ 类 & 对象C++ クラス & オブジェクト

C++ のクラスへのポインタは構造体へのポインタと似ており、クラスへのポインタのメンバーにアクセスするにはメンバーアクセス演算子を使用する必要があります。->構造体へのポインタにアクセスするのと同じです。すべてのポインタと同様に、ポインタを使用する前に初期化する必要があります。

C++ では、クラスへのポインタはクラスのオブジェクトを指します。通常のポインタと同様に、クラスへのポインタを使用してオブジェクトのメンバー変数とメンバー関数にアクセスできます。

クラスへのポインタの宣言と初期化

サンプル

#include <iostream>

class MyClass {
public:
    int data;

    void display() {
        std::cout << "Data: " << data << std::endl;
    }
};

int main() {
    // クラスオブジェクトを作成
    MyClass obj;
    obj.data = 42;

    // クラスへのポインタを宣言して初期化
    MyClass *ptr = &obj;

    // ポインタを介してメンバー変数にアクセス
    std::cout << "Data via pointer: " << ptr->data << std::endl;

    // ポインタを介してメンバー関数を呼び出す
    ptr->display();

    return 0;
}

上記のコードがコンパイルおよび実行されると、次の結果が生成されます。

Data via pointer: 42
Data: 42

動的メモリ割り当て

クラスへのポインタは、動的にメモリを割り当ててクラスのオブジェクトを作成するためにも使用できます。

サンプル

#include <iostream>

class MyClass {
public:
    int data;

    void display() {
        std::cout << "Data: " << data << std::endl;
    }
};

int main() {
    // メモリを動的割り当てしてクラスオブジェクトを作成
    MyClass *ptr = new MyClass;
    ptr->data = 42;

    // ポインタを介してメンバー関数を呼び出す
    ptr->display();

    // 動的に割り当てられたメモリを解放
    delete ptr;

    return 0;
}

上記のコードがコンパイルおよび実行されると、次の結果が生成されます。

Data: 42

関数パラメータとしてのクラスへのポインタ

クラスへのポインタは関数パラメータとして渡すことができます。

サンプル

#include <iostream>

class MyClass {
public:
    int data;

    void display() {
        std::cout << "Data: " << data << std::endl;
    }
};

// 関数はクラスへのポインタをパラメータとして受け取る
void processObject(MyClass *ptr) {
    ptr->display();
}

int main() {
    MyClass obj;
    obj.data = 42;

    // クラスへのポインタを関数に渡す
    processObject(&obj);

    return 0;
}

サンプル

次の例は、クラスへのポインタの概念をよりよく理解するのに役立ちます。

サンプル

#include <iostream>
 
using namespace std;

class Box
{
   public:
      // コンストラクタの定義
      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 pointer to a class.

   // 最初のオブジェクトのアドレスを保存
   ptrBox = &Box1;

   // メンバーアクセス演算子を使用してメンバーにアクセスしてみる
   cout << "Volume of Box1: " << ptrBox->Volume() << endl;

   // 2番目のオブジェクトのアドレスを保存
   ptrBox = &Box2;

   // メンバーアクセス演算子を使用してメンバーにアクセスしてみる
   cout << "Volume of Box2: " << ptrBox->Volume() << endl;
 
   return 0;
}

上記のコードがコンパイルおよび実行されると、次の結果が生成されます。

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

C++ 类 & 对象C++ クラス & オブジェクト

その他の拡張