一個指向 C++ 類的指針與指向結構的指針類似,訪問指向類的指針的成員,需要使用成員訪問運算符 ->,就像訪問指向結構的指針一樣。
與所有的指針一樣,您必須在使用指針之前,對指針進行初始化。
下面的實例有助于更好地理解指向類的指針的概念:
#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;
// 保存第二個對象的地址
ptrBox = &Box2;
// 現在嘗試使用成員訪問運算符來訪問成員
cout << "Volume of Box2: " << ptrBox->Volume() << endl;
return 0;
}
當上面的代碼被編譯和執行時,它會產生下列結果:
Constructor called.
Constructor called.
Volume of Box1: 5.94
Volume of Box2: 102
代碼鏈接:https://github.com/karst87/cpp/tree/master/learning/com.runoob