指向const变量的指针去当参数形参的好处
2012-10-21 19:35
211 查看
指向const变量的指针去当参数形参的好处, 在编写一个函数时,当已经确定这个函数不会更新数据值只是读取的话,就把指向const变量的指针设置成参数吧. 就算实参是非const变量也没有关系的哦.都能保证函数的正确性,都能保护形参指针所指向的对象,使其在函数执行中不被修改,这就是你在大量的代码示例中看到const class * 型指针的原因了.
int main(int argc,
const
char * argv[])
{
void printTime(const
Time * p);
//static Time time1(12,12,12);
Time * timeNotConst =
new Time(12,12,12);
const Time * timeOfConst =
new Time(12,12,13);
printTime(timeNotConst);
printTime(timeOfConst);
//声明一个类函数成员的指针
// void (Time::* p)(int)=&Time::get_time;//后面的函数名与参数无关
//delete time1;
delete timeNotConst ;
delete timeOfConst;
return
0;
}
void printTime(const
Time * p){
(*p).get_time();
};
Constructor called!
Constructor called!
12:12:12
12:12:13
int main(int argc,
const
char * argv[])
{
void printTime(const
Time * p);
//static Time time1(12,12,12);
Time * timeNotConst =
new Time(12,12,12);
const Time * timeOfConst =
new Time(12,12,13);
printTime(timeNotConst);
printTime(timeOfConst);
//声明一个类函数成员的指针
// void (Time::* p)(int)=&Time::get_time;//后面的函数名与参数无关
//delete time1;
delete timeNotConst ;
delete timeOfConst;
return
0;
}
void printTime(const
Time * p){
(*p).get_time();
};
Constructor called!
Constructor called!
12:12:12
12:12:13
相关文章推荐
- 形参是指向非const型变量指针,实参是const变量指针,参数传递非法
- const->形式参数、指向常量数据的指针、指针常量
- 用变量a给出下面的定义:一个有10个指针的数组,该指针指向一个函数,该函数有一个整形参数并返回一个整型数
- 指向结构体变量的指针作函数参数
- 实参和形参指针做函数参数时,如何改变main函数变量的值
- [C++] C++中const修饰指针,变量, 函数参数和函数返回值的用法总结
- 不能通过改变形参指针的值(形参所指向的地址)来改变实参指针的地址,实现改变实参指针所指向地址变量的值。
- C语言_结构体变量指针做函数参数的使用案例
- C语言第12天 指向变量的指针
- C++指向const对象的指针和const指针
- 用指向函数的指针作函数参数
- const 详解(修饰变量、输入参数、返回值、成员函数)
- 用指向数组的指针作函数参数
- 用指向数组的指针作函数参数.etc
- 细嚼慢咽C++primer(3)——引用形参,内联函数,重载函数,指向函数的指针
- 建立一个对象数组,内放5个学生数据(学号、成绩),设立一个函数max,用指向对象的指针作函数参数,在max函数中找出5个学生中成绩最高者,并从输出学号。
- 指针数组,指针指向const成员函数
- this指针与function变量--this究竟指向哪里?
- C语言 指向结构体变量的指针
- const形参,何时创建临时变量