C++ 中指向类的指针
c++ 中指向类的指针
一个指向 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

c++ 类和对象
