这是一个小测试程序:
#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.
标准规定不需要通过实例调用方法,并不代表你不能这样做.甚至还有一个使用它的例子:
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
}
这篇关于C++ 类实例上的静态成员方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!