我可以在 C++ 中声明非成员函数 const 吗?
我可以在 C++ 中将非成员函数(可能是全局函数)声明为 const 吗?我知道 const 关键字实际上应用于成员函数中传递的隐式“this”参数。另外,由于只有成员函数遵循“thiscall”调用约定,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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不可以,只有非静态成员函数可以是 const 限定的。
您期望 const 非成员函数具有什么语义?如果您想强制函数不修改任何参数,只需通过 const 引用获取它们即可。
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.
回答你的第二个问题:尝试对非成员使用成员函数语法(即
void foo() const;
)是语法违规。因此,编译器必须给出诊断 - 错误或警告。它可能不会默默地忽略const
。但是,它可能会报告警告,然后假装 const 不存在并生成可执行文件。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 theconst
. However, it may report a warning, then pretend theconst
wasn't there and produce an executable.