一个指向 C++ 类的指针与指向结构的指针类似,访问指向类的指针的成员,需要使用成员访问运算符 ->
,就像访问指向结构的指针一样。与所有的指针一样,必须在使用指针之前,对指针进行初始化。
实例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| #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; double breadth; double height; };
int main(void) { Box Box1(3.3, 1.2, 1.5); Box Box2(8.5, 6.0, 2.0); Box *ptrBox;
ptrBox = &Box1;
cout << "Volume of Box1: " << ptrBox->Volume() << endl;
ptrBox = &Box2;
cout << "Volume of Box2: " << ptrBox->Volume() << endl;
return 0; }
|
结果:
1 2 3 4
| Constructor called. Constructor called. Volume of Box1: 5.94 Volume of Box2: 102
|
C++ 指向类的指针