欢迎光临散文网 会员登陆 & 注册

类指针学习1.1|C++类指针例子

2022-01-03 23:32 作者:LogByMax  | 我要投稿


#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 Box3(3, 7.0, 1.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;

   

   // 保存第三个对象的地址

   ptrBox = &Box3;

   // 现在尝试使用成员访问运算符来访问成员

   cout << "Volume of Box3: " << ptrBox->Volume() << endl;

  

   return 0;

}

输出结果:

Constructor called.

Constructor called.

Constructor called.

Volume of Box1: 5.94

Volume of Box2: 102

Volume of Box3: 21


=reference=

[1]https://www.runoob.com/cplusplus/cpp-pointer-to-class.html

类指针学习1.1|C++类指针例子的评论 (共 条)

分享到微博请遵守国家法律