C++ 类实例上的静态成员方法调用

2021-12-22 00:00:00 standards visual-c++ c++

这是一个小测试程序:

#include <iostream>

class Test
{
public:
    static void DoCrash(){ std::cout<< "TEST IT!"<< std::endl; }
};

int main()
{
    Test k;
    k.DoCrash(); // calling a static method like a member method...

    std::system("pause");

    return 0;
}

在 VS2008 + SP1 (vc9) 上它编译得很好:控制台只显示TEST IT!".

On VS2008 + SP1 (vc9) it compiles fine: the console just display "TEST IT!".

据我所知,不应在实例化对象上调用静态成员方法.

As far as I know, static member methods shouldn't be called on instanced object.

  1. 我错了吗?从标准的角度来看,此代码是否正确?
  2. 如果正确,为什么会这样?我不知道为什么允许这样做,或者是为了帮助在模板中使用静态与否"方法?

推荐答案

标准规定不需要通过实例调用方法,并不代表你不能这样做.甚至还有一个使用它的例子:

The standard states that it is not necessary to call the method through an instance, that does not mean that you cannot do it. There is even an example where it is used:

C++03, 9.4 静态成员

C++03, 9.4 static members

类 X 的静态成员 s 可以使用限定 id 表达式 X::s;它是没有必要使用类成员访问语法(5.2.5)来引用到静态成员.静态成员可能使用类成员访问语法来引用,其中如果对象表达式是评价.

A static member s of class X may be referred to using the qualified-id expression X::s; it is not necessary to use the class member access syntax (5.2.5) to refer to a static member. A static member may be referred to using the class member access syntax, in which case the object-expression is evaluated.

class process {
public:
   static void reschedule();
};

process& g();

void f()
{
   process::reschedule(); // OK: no object necessary             
   g().reschedule(); // g() is called
}

相关文章