const 用法详解

当不想从外部调用成员函数修改成员变量时,可以将其被调成员函数加上const

每个成员函数都有个隐式 this 指针,指向调用对象

 

ContractedBlock.gifExpandedBlockStart.gif代码
1 // CBox 类头文件
2  #pragma once
3 #include <iostream>
4  using namespace std;
5
6  class CBox
7 {
8 public:
9 CBox(double lv = 1.0, double lw = 1.0, double lh = 1.0);
10
11 public:
12 double Volume( void ) const;
13 int Compare( CBox xBox ) const;
14
15 private:
16 double m_Length;
17 double m_Width;
18 double m_Height;
19 };

20

21 // CBox 类源文件
22 #include "Box.h"
23
24 // 构造函数
25 CBox::CBox(double lv, double lw, double lh)
26 : m_Length(lv),m_Width(lw),m_Height(lh)
27 {
28 cout << "构造函数" << endl;
29 }
30
31 // 计算盒子体积
32 double CBox::Volume( void ) const
33 {
34 return m_Length * m_Width * m_Height;
35 }
36
37 // 比较两个盒子体积大小
38 int CBox::Compare( CBox xBox ) const
39 {
40 return this->Volume() > xBox.Volume();
41 }

 

 

 

上面的 this->Volume() > xBox.Volume(); 其实就是调用对象与被传过来的 xBox 对象进行比较。

 

ContractedBlock.gifExpandedBlockStart.gif代码
// main 函数
#include "Box.h"

int main( void )
{
CBox box1(
2.0, 3.0, 4.0);
CBox box2(
1.0, 2.0, 3.0);
cout
<< "box1.Volume() = " << box1.Volume() << endl;
cout
<< "box2.Volume() = " << box2.Volume() << endl;

if (box1.Compare(box2))
{
cout
<< "box1的体积大于box2" << endl;
}
else
{
cout
<< "box1的体积小于或等于box2" << endl;
}

system(
"pause");
return 0;
}

 

转载于:https://www.cnblogs.com/cuck/archive/2010/03/21/1691242.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值