IamEasy_Man

Filled With Confidence , And Never Say Give Up !

【原创】const实参和const常量形参

利用指针或者应用作为参数按应用进行传递,可以减少系统的开销。因为假如参数是一个大型的数据对象的时候,直接将其作为参数的话是将其Copy一份作为函数的参数,这比起按应用传输会花费更多的系统的开销。将函数的传值没什么好讲的,做程序员的,大家都必比较清楚了,记录一下而已。

自己写的一个Demo代码如下:


// C++BaseTest.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <windows.h>
#include <iostream>
using namespace std;

void Func_One(int*);
void Func_Two(int);
void Func_Three(const int*);
void Func_Four(const int);

int _tmain(int argc, _TCHAR* argv[])
{
    
int a = 8;
    
int* a_ptr = &a;
    
const int* a_const_ptr = &a;
    
const int a_const = 9;

    
//Func_Two(a);
    
//Func_Two(a_const);

    
//Func_One(a_ptr);
    
//Func_One(a_const_ptr);       //Error:const int* 不能转换为 int*

    
//Func_Three(a_ptr);
    
//Func_Three(a_const_ptr);

    Func_Four(a);
    Func_Four(a_const);

    
while(true)
        
{
    }

    
return 0;
}


void Func_One(int* a)

    cout<<"Func_One"<<endl;
}

void Func_Two(int a)
{
    cout<<"Func_Two"<<endl;
}

void Func_Three(const int* a)
{
    cout<<"Func_Three"<<endl;
}

void Func_Four(const int a)
{
    cout<<"Func_Four"<<endl;
}
  上面的Demo只有在执行Func_One的时候当形参为整型指针,而实参为const定义的指针时会报错。这是为什么呢?个人觉得,在Func_One函数中形参是整型指针,也就是说假如在函数体内对传入的实参所指向的数据做修改会有效的,但是实参却是由const定义的一个常量指针,它不允许修改指针以及指针说指向的内容,为了避免矛盾的发生,编译器会认为这样是错误的。而为什么在Func_Two中,无论实参是否定义const都能正常通过呢?这很简单,实参传递给函数只是Copy了一份给它,函数并不会改变实参的值,所以这是允许的。Func_Three虽然形参是以指针的形式来表示,但是由const来定义,就说明了假如函数对实参做任何的修改都是不合语法的。Func_Four同理。
  其实只需要明白一点,const定义的任何常量在任何情况之下都是不允许被改变的。

posted on 2009-09-25 21:40  IamEasy_Man  阅读(1313)  评论(0)    收藏  举报

导航