C++ | C++ 类 & 对象 | 指向类的指针

C++ 指向类的指针

一个指向 C++ 类的指针与指向结构的指针类似,访问指向类的指针的成员,需要使用成员访问运算符 ->,就像访问指向结构的指针一样。
与所有的指针一样,您必须在使用指针之前,对指针进行初始化。

实例1:

/*******************************************************************
* > File Name: classPointer.cpp
* > Create Time: 2021年09月 3日 14:48:01
******************************************************************/
#include <iostream>
using namespace std;

class Box{
public:
Box(double l = 2.0, double w = 2.0, double h = 2.0)
{
cout << "calling constructor" << endl;
length = l;
width = w;
heigth = h;
}
double volume(void)
{
return (length*width*heigth);
}
protected:
private:
double length;
double width;
double heigth;
};

int main(void)
{
Box box1(2.0, 3.0, 4.0); /* 声明一个对象box1 */
Box box2(3.0, 4.0, 5.0); /* 声明一个对象box2 */
Box* pbox; /* 声明一个Box类型的指针变量 */

pbox = &box1; /* 获取对象box1的地址 */
cout << "the volume of box1: " << pbox->volume() << endl; /* 使用访问运算符访问 */
pbox = &box2; /* 获取对象box2的地址 */
cout << "the volume of box2: " << pbox->volume() << endl; /* 使用访问运算符访问 */

return 0;
}

编译、运行:

PS E:\fly-prj\cplusplus\day5> make 
g++ -o classPointer classPointer.cpp -g -Wall
PS E:\fly-prj\cplusplus\day5> .\classPointer.exe
calling constructor
calling constructor
the volume of box1: 24
the volume of box2: 60