简体   繁体   中英

Can I declare a non-member function const in C++?

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.

To answer your second question: an attempt to use the member function syntax for a non-member (ie void foo() const; ) is a grammar violation. Therefore, a compiler must give a diagnostic - either an error or a warning. It may not silently ignore the const . However, it may report a warning, then pretend the const wasn't there and produce an executable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM