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

2019-02-03 13:23发布

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?

2条回答
Viruses.
2楼-- · 2019-02-03 14:02

To answer your second question: an attempt to use the member function syntax for a non-member (i.e. 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.

查看更多
一夜七次
3楼-- · 2019-02-03 14:07

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.

查看更多
登录 后发表回答