C++之指向类的指针

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

废话不多说,上代码:

#include <iostream>

using namespace std;

class Box {
private:
    double length;     // 长
    double width;      // 宽
    double height;     // 高
public:
    // 构造函数定义
    Box(double l = 2.0, double b = 2.0, double h = 2.0) {
        cout << "Constructor called." << endl;
        length = l;
        width = b;
        height = h;
    }

    double Volume() {
        return length * width * height;
    }
};

int main() {
    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

Process finished with exit code 0

类指针非常简单,我们先初始化指针变量,然后将指针变量->调用方法即可。

猜你喜欢

转载自blog.csdn.net/qq_33567641/article/details/81195465
今日推荐