C++入门基础知识145—【关于C++ 指向类的指针】

 成长路上不孤单

【14后///计算机爱好者///持续分享所学///如有需要欢迎收藏转发///】

今日分享关于C++  指向类的指针的相关内容!

关于【C++ 指向类的指针】

一个指向 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

#include

using namespace std;

class Box

{

   public:

      // 构造函数定义

      Box(double l=2.0double b=2.0double 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.31.21.5);    // Declare box1

   Box Box2(8.56.02.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;

}

当上面的代码被编译和执行时,它会产生下列结果:

C++入门基础知识145—【关于C++ 指向类的指针】_第1张图片

你可能感兴趣的:(学习,c++,开发语言,人工智能,学习,微信小程序,微信开放平台)