这是一个小测试程序:
#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模板网!
读取输入文件,最快的方法?read input files, fastest way possible?(读取输入文件,最快的方法?)
在 C++ 中读取格式化输入的最简单方法?The easiest way to read formatted input in C++?(在 C++ 中读取格式化输入的最简单方法?)
从 .txt 文件读取到 C++ 中的二维数组Reading from .txt file into two dimensional array in c++(从 .txt 文件读取到 C++ 中的二维数组)
如何在 C++ 中模拟按键按下How to simulate a key press in C++(如何在 C++ 中模拟按键按下)
为什么在 cin.ignore() 之后没有 getline(cin, var) 读取Why doesn#39;t getline(cin, var) after cin.ignore() read the first character of the string?(为什么在 cin.ignore() 之后没有 getline(cin, var) 读取
scanf 格式输入的 cin 类比是什么?What is the cin analougus of scanf formatted input?(scanf 格式输入的 cin 类比是什么?)