const方法

本文深入探讨了C++中const关键字的多种用途及其在实际编程中的应用技巧。包括定义常量、保护对象免受意外修改、节省内存空间等方面的作用,并通过具体示例对比了const与宏定义的区别。此外,还解析了const在成员函数声明中的含义及其对函数行为的影响。

1、先看下一个类

Test.h

 1 #define PI  3.14159
 2 const int NUM = 3;//定义常量
 3 class Test
 4 {
 5 public:
 6        Test();
 7        virtual ~Test();
 8        virtual void action(const int input);//保护,防止意外修改
 9        int getstate() const;
10        const MyClass istate();
11 private:
12        static int mLay;
13        int mOut;
14 
15 };

Test.cpp

 1 #include <iostream>
 2 #include "Test.h"
 3 
 4 using namespace std;
 5 
 6 Test::Test():mOut(1)
 7 {
 8 }
 9 Test::~Test()
10 {
11 }
12 void Test::action(const int input)
13 {
14   input++;
15 }
16 
17 int Test::getstate() const
18 {
19   return (mOut);
20 }
21 const int Test::istate()
22 {
23   mOut++;
24   return (mOut);
25 }

consttest.cpp

 1 // consttest.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include "Test.h"
 6 
 7 int _tmain(int argc, _TCHAR* argv[])
 8 {
 9     Test test;
10     int mFi = 9;
11     test.action(mFi);
12     return 0;
13 }

2、(1)以上程序编译,consttest.cpp---11行 会报错,因为不能给常量赋值。

    (2)const定义常量从汇编的角度来看,只是给出了对应的内存地址,而不是象#define一样给出的是立即数,所以,const定义的常量在程序运行过程中只有一份拷贝,而#define定义的常量在内存中有若干个拷贝。因此使用const来定义常量比宏定义更能提高效率。

总结const作用有以下:

   (1)定义常量;(2)保护,防止意外修改;(3)节省空间,避免不必要的内存分配;

3、int getstate() const与const MyClass istate() 区别;

    int getstate() const:这里的const表明与客户代码的一个合约,即保证你不会在此方法中尝试修改对象的内部值,如果修改编译器将会报错,如例子1所示。

    const MyClass istate() :这里的const表明,函数返回值型不可以被改变,函数返回什么类型,就要赋给什么类型。

例子1  Test.cpp

 1 #include <iostream>
 2 #include "Test.h"
 3 
 4 using namespace std;
 5 
 6 Test::Test():mOut(1)
 7 {
 8 }
 9 Test::~Test()
10 {
11 }
12 void Test::action(const int input)
13 {
14  
15 }
16 
17 int Test::getstate() const
18 {
19   mOut++;//此句修改内部值,将报错
20   return (mOut);
21 }
22 const int Test::istate()
23 {
24   mOut++;
25   return (mOut);
26 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值