简体   繁体   English

我可以在C ++中声明一个非成员函数const吗?

[英]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++? 我可以在C ++中将非成员函数(可能是全局函数)声明为const吗? I understand that the const keyword actually is applied to the implicit "this" argument passed in member functions. 我知道const关键字实际上应用于成员函数中传递的隐式“ this”参数。 Also since only member functions follow the "thiscall" calling convention, can const be applied for non-member functions? 另外,由于仅成员函数遵循“ thiscall”调用约定,因此const可以应用于非成员函数吗?

Leaving aside what I am trying to do by declaring non-member function const, would compiler report error for doing so? 抛开声明非成员函数const所做的尝试,编译器是否会报告这样做的错误?

No, only a non-static member function may be const qualified. 不可以,只有非静态成员函数才可以被const限定。

What semantic would you expect from a const non-member function ? 您希望const非成员函数具有什么语义? If you want to enforce that no parameters are modified by the function, just take them by const reference. 如果要强制该函数不修改任何参数,只需通过const引用即可。

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. 回答您的第二个问题:尝试对非成员使用成员函数语法(即void foo() const; )是违反语法的。 Therefore, a compiler must give a diagnostic - either an error or a warning. 因此,编译器必须给出诊断-错误或警告。 It may not silently ignore the const . 它可能不会默默地忽略const However, it may report a warning, then pretend the const wasn't there and produce an executable. 但是,它可能会报告警告,然后假装const不存在并生成可执行文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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