C++中const有什么作用

本文深入探讨C++中const关键字的多种用途,包括定义常量、优化函数参数传递、保护返回值及成员函数的正确使用。通过具体代码示例,揭示const如何提升程序的安全性和效率。

摘自:C和C++程序员面试秘籍

(1)const用于定义常量:const定义的常量编译器可以对其进行数据静态类型安全检查。
(2)const修饰函数形式参数:当输入参数为用户自定义类型和抽象数据类型时,应该将值传递改为const &传递,可以提高效率。比较下面两段代码:

void fun(A a);
void fun(A const &a);

第一个函数效率低。函数体内产生A类型的临时对象用于复制参数a,临时对象的构造、复制、析构过程都将消耗时间。而第二个函数提高了效率。用引用传递不需要产生临时对象,节省了临时对象的构造、复制、析构过程消耗的时间。但是只有引用有可能会改变a,所以加const。
(3)const修饰函数的返回值:如给指针传递的函数返回值加const,则返回值不能被直接修改,且该返回值只能被赋值给加const修饰的同类型的指针,例如:

const char *GetChar(void){};
char *ch = GetChar();     //error
const char *ch = GetChar();   //correct

(4)const修饰类的成员函数(函数定义体):任何不会修饰数据成员的函数都应用const修饰,这样,当不小心修改了数据成员或调用了非const成员函数时,编译器都会报错。const修饰类的成员函数形式为:

int GetCount(void) const;
The TPS54331 is a 28-V, 3-A non-synchronous buck Integrated 80 mΩ High Side MOSFET Supports up to 3A Continuous Output Current converter that integrates a low Rds(on) high side MOSFET. To increase efficiency at light loads, a pulse skipping Eco-mode™ feature is automatically High Efficiency at Light Loads with a Pulse activated. Furthermore, the 1 A shutdown supply Skipping Eco-mode™ current allows the device to be used in battery Fixed 570kHz Switching Frequency Typical 1A Shutdown Quiescent Current powered applications. Current mode control with internal slope compensation simplifies the external compensation calculations and reduces component Adjustable Slow Start Limits Inrush Currents count while allowing the use of ceramic output Programmable UVLO Threshold Overvoltage Transient Protection capacitors. A resistor divider programs the hysterisis of the input under-voltage lockout. An overvoltage transient protection circuit limits voltage overshoots Cycle by Cycle Current Limit, Frequency Fold during startup and transient conditions. A cycle by Back and Thermal Shutdown Protection cycle current limit scheme, frequency fold back and Available in Easy-to-Use SOIC8 Package Supported by SwitcherPro™ Software Tool (http://focus.ti.com/docs/toolsw/folders/print/s witcherpro.html) For SWIFT™ Documentation, See the TI Website at www.ti.com/swift thermal shutdown protect the device and the load in the event of an overload condition. The TPS54331 is available in an 8-pin SOIC package that has been internally optimized to improve thermal performance.
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值