为什么没有“const-correctness”的概念。为类的静态成员函数? [英] Why there is no concept of "const-correctness" for class's static member functions?

查看:117
本文介绍了为什么没有“const-correctness”的概念。为类的静态成员函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用案例:

class A {
  static int s_common;
public:
  static int getCommon () const { s_common; };
};

通常这会导致错误:

错误:static成员函数'static int A :: getCommon()'不能有
cv-qualifier

error: static member function ‘static int A::getCommon()’ cannot have cv-qualifier


b $ b

这是因为 const ness仅适用于 this 指向的对象,在 static 成员函数中。

This is because constness applies only to the object pointed by this, which is not present in a static member function.

但是如果允许, static 成员函数的const可以很容易地与 static 数据成员相关。

为什么这个特性不存在C ++;它的任何逻辑原因?

However had it been allowed, the static member function's "const"ness could have been easily related to the static data members.
Why is this feature is not present in C++; any logical reason behind it ?

推荐答案

cv-qualifiers 签名。所以你可以有:

cv-qualifiers affect the function's signature. So you could have:

class A {
  static int s_common;
public:
  static void getCommon () const {  };
  static void getCommon () {  };
};

现在...你如何调用 const one?没有 const 对象来调用它(嗯,你可以在 const 对象上调用它,但这不是点)。

Now... how would you call the const one? There's no const object to call it on (well, you could call it on a const object, but that's not the point).

我只是在这里猜,可能有其他原因。 :)

I'm just guessing here, there probably are other reasons. :)

这篇关于为什么没有“const-correctness”的概念。为类的静态成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆