C ++对类实例的静态成员方法调用 [英] C++ Static member method call on class instance

查看:118
本文介绍了C ++对类实例的静态成员方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是一个小测试程序:

  #include< iostream> 

class Test
{
public:

static void DoCrash(){std :: cout< 测试!< std :: endl; }


};


int main()
{
Test k;
k.DoCrash(); //调用一个静态方法,如成员方法...

std :: system(pause);

return 0;在VS2008 + SP1(vc9)它编译良好:控制台只显示


$ b $ p <测试它!。



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


  1. 我错了吗?这个代码从标准的角度来看是否正确?

  2. 如果是正确的,为什么?我不知道为什么会被允许,或者也许是帮助在模板中使用静态或不是方法。


解决方案

标准规定没有必要通过实例调用方法,这并不意味着你不能这样做。甚至有一个使用它的示例:



C ++ 03,9.4静态成员


类X的静态成员可以使用
qualified-id表达式X :: s来引用;它是
不必使用类成员访问语法(5.2.5)将
引用到静态成员。可以使用类成员访问语法来引用静态成员
,其中
case表示对象表达式是


< blockquote>

  [示例:
类进程{
public:
static void reschedule
};
process& G();
void f()
{
process :: reschedule(); // OK:no object necessary
g()。reschedule(); // g()调用
} -end example]


Here is a little test program :

#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;
}

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. Am I wrong? Is this code correct from the standard point of view?
  2. If it's correct, why is that? I can't find why it would be allowed, or maybe it's to help using "static or not" method in templates?

解决方案

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 static members

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.

[Example:
class process {
public:
   static void reschedule();
};
process& g();
void f()
{
   process::reschedule(); // OK: no object necessary             
   g().reschedule(); // g() is called
}  —end example]

这篇关于C ++对类实例的静态成员方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆