我可以在C ++中声明一个非成员函数const吗? [英] Can I declare a non-member function const in C++?

查看:147
本文介绍了我可以在C ++中声明一个非成员函数const吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在C ++中声明一个非成员函数(全局函数,可能)为const吗?我明白const关键字实际上应用于在成员函数中传递的隐式this参数。也因为只有成员函数遵循thiscall调用约定,const可以用于非成员函数吗?

抛开我想通过声明非成员函数const来做什么,编译器会报错吗?

解决方案

不,只有非静态成员函数可能是 const 合格。

您对const非成员函数的期望是什么?如果你想强制这个函数没有修改任何参数,只需通过const引用就可以了。


Can I declare a non-member function (global function, may be) as const in C++? I understand that the const keyword actually is applied to the implicit "this" argument passed in member functions. Also since only member functions follow the "thiscall" calling convention, can const be applied for non-member functions?

Leaving aside what I am trying to do by declaring non-member function const, would compiler report error for doing so?

解决方案

No, only a non-static member function may be const qualified.

What semantic would you expect from a const non-member function ? If you want to enforce that no parameters are modified by the function, just take them by const reference.

这篇关于我可以在C ++中声明一个非成员函数const吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆