Why can't a static member function have a cv-qualifier?

问题

如果你写出了如下代码

class A
{
public:
	static void foo() const { }
};

那么编译会报: static member function ‘static void A::foo()’ cannot have cv-qualifier.

为什么

c++标准了解一下:

  1. A static member function does not have a this pointer.
  2. A static member function shall not be virtual.
  3. There shall not be a static and a non-static member function with the same name and the same parameter types.
  4. A static member function shall not be declared const, volatile, or const volatile.

由上面可以看出来, const尾部修饰符的作用: 将类成员函数中的this指针从T*变为T const*. 而静态函数没有this指针, 所以也就不需要const尾部修饰.

当然上面这个并不是解释. 最标准的解释就是c++标准不允许. 至于为什么不允许, 也许就是标准委员会是基于上面的这个原因来考虑的.

猜你喜欢

转载自blog.csdn.net/creambean/article/details/88691990