C++ 中指向類的指針
c++ 中指向類的指針
一個指向 c++ 類的指針與指向結(jié)構(gòu)的指針類似,訪問指向類的指針的成員,需要使用成員訪問運算符 ->,就像訪問指向結(jié)構(gòu)的指針一樣。與所有的指針一樣,您必須在使用指針之前,對指針進(jìn)行初始化。
下面的實例有助于更好地理解指向類的指針的概念:
#include <iostream> using namespace std; class box { public: // 構(gòu)造函數(shù)定義 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; // 現(xiàn)在嘗試使用成員訪問運算符來訪問成員 cout << "volume of box1: " << ptrbox->volume() << endl; // 保存第二個對象的地址 ptrbox = &box2; // 現(xiàn)在嘗試使用成員訪問運算符來訪問成員 cout << "volume of box2: " << ptrbox->volume() << endl; return 0; }
當(dāng)上面的代碼被編譯和執(zhí)行時,它會產(chǎn)生下列結(jié)果:
constructor called. constructor called. volume of box1: 5.94 volume of box2: 102