问题描述
这是一个小测试程序:
#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设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)