void const f() vs void f() const

本文深入探讨了C++中const成员函数的概念及其使用场景。解释了如何通过const限定符来确保成员函数不会修改对象的状态,以及如何通过const对象调用这些函数。同时,文章对比了const与非const成员函数的区别,以及它们在类设计中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

void const f() is equivilent to const void f(), which means the return type (in this case a void) is const. This is totally meaningless not only because it's a void (there is nothing there that needs a const qualifier), but also because it's a return type (returning something as const doesn't make a whole lot of sense).

void f() const makes the function itself const. This only really has meaning for member functions. Making a member function const means that it cannot call any non-const member functions, nor can it change any member variables. It also means that the function can be called via a const object of the class:

class A
{
public:
  void Const_No();   // nonconst member function
  void Const_Yes() const; // const member function
};


//-----------

A  obj_nonconst;  // nonconst object
obj_nonconst.Const_No();  // works fine
obj_nonconst.Const_Yes(); // works fine

const A obj_const = A(); // const object
obj_const.Const_Yes(); // works fine (const object can call const function)
obj_const.Const_No();  // ERROR (const object cannot call nonconst function)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值