C++编程基础二 22-this指针

 1 #pragma once
 2 
 3 #ifndef CUBOID_H_
 4 #define CUBOID_H_
 5 
 6 
 7 class Cuboid
 8 {
 9 private:
10     double length_;
11     double width_;
12     double height_;
13 public:
14     Cuboid(double length, double width, double height); //构造函数
15     Cuboid(); //无参数的构造函数
16     ~Cuboid(); //析构函数
17     double volume() { return length_ * width_*height_; }; //体积
18     int compare(Cuboid &c);
19 };
20 
21 
22 #endif // !CUBOID_H_
 1 #include "stdafx.h"
 2 #include "Cuboid.h"
 3 
 4 
 5 Cuboid::Cuboid(double length, double width, double height)
 6 {
 7     length_ = length;
 8     width_ = width;
 9     height_ = height;
10 }
11 
12 Cuboid::Cuboid()
13 {
14 }
15 
16 
17 Cuboid::~Cuboid()
18 {
19 }
20 
21 int Cuboid::compare(Cuboid & c)
22 {
23     if(this->volume()>c.volume())  //对象用() ,指针用(->)
24     {
25         return 0;
26     }
27     else if (this->volume() == c.volume())
28     {
29         return 1;
30     }
31     else
32     {
33         return 2;
34     }
35     
36 }
 1 // C++函数和类 22-this指针.cpp: 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include "Cuboid.h"
 6 #include<iostream>
 7 using namespace std;
 8 
 9 int main()
10 {
11     Cuboid c1(4, 4, 3);
12     Cuboid c2(4, 4, 4);
13     int res = c1.compare(c2);
14     if (res == 0)
15     {
16         cout << "第一个长方体的体积大于第二个长方体的体积" << endl;
17     }
18     else if(res==1)
19     {
20         cout << "两个长方体的体积相等" << endl;
21     }
22     else
23     {
24         cout << "第一个长方体的体积小于第二个长方体的体积" << endl;
25     }
26     return 0;
27 }

猜你喜欢

转载自www.cnblogs.com/uimodel/p/9348631.html