C++ Static member method call on class instance(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.
- 我错了吗?从标准的角度来看,此代码是否正确?
- 如果正确,为什么会这样?我不知道为什么允许这样做,或者是为了帮助在模板中使用静态与否"方法?
推荐答案
标准规定不需要通过实例调用方法,并不代表你不能这样做.甚至还有一个使用它的例子:
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++ 类实例上的静态成员方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 类实例上的静态成员方法调用


基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 这个宏可以转换成函数吗? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01