简体   繁体   English

'static'是否为c ++类成员函数?

[英]'static' for c++ class member functions?

Why is the static keyword necessary at all? 为什么静态关键字是必需的?

Why can't the compiler infer whether it's 'static' or not? 为什么编译器不能推断它是否是“静态的”?

As follows: 如下:

Can I compile this function without access to non-static member data? 我可以在不访问非静态成员数据的情况下编译此函数吗? Yes -> static funcion. 是的 - >静态功能。 No -> non-static function. 否 - >非静态功能。

Is there any reason this isn't inferred? 有没有理由不推断这个?

如果您希望编译器在现场决定它是否是静态的,那么它如何影响链接到仅定义方法签名的头文件的外部源文件?

The propery of being static or non-static affects the function type. 静态或非静态的功能会影响功能类型。 Non-static member functions have an implicit this parameter, while static ones don't, for one example. 例如,非静态成员函数具有隐式this参数,而静态成员函数则不具有隐式this参数。

In other words, there's a major qualitative difference between static and non-static member functions. 换句话说,静态和非静态成员函数之间存在重大的质量差异。 The compiler cannot "infer" this. 编译器不能“推断”这个。 This is a matter of the author's intent. 这是作者的意图问题。

If I want (and need) my function to be non-static, I make it non-static, even if it doesn't access any non-static members of the class. 如果我希望(并且需要)我的函数是非静态的,我将它设置为非静态的,即使它不访问类的任何非静态成员。 If the compiler suddently decides to make my non-static function static just because it doesn't access any non-static members of the class, in general case it will destroy the functionality of the code. 如果编译器突然决定让我的非静态函数静态,因为它不访问类的任何非静态成员,一般情况下它会破坏代码的功能。

Yes the compiler could, but it has no knowledge of your intent. 是的,编译器可以,但它不知道你的意图。 And the original designers probably thought that supplying your intent was important. 原始设计师可能认为提供你的意图非常重要。

在语言中具有这样的冗余有助于确保许多程序员错误最终会被编译器捕获。

Another reason: If the function is static, it can't be overridden in derived classes. 另一个原因:如果函数是静态的,则不能在派生类中重写它。 No polymorphism. 没有多态性。

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

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