简体   繁体   English

C ++:在没有对象实例的情况下调用非静态成员函数

[英]C++: calling non-static member function without instance of object

I'm looking at the source code for the Godot game engine, and came across the following (some omitted for simplicity): 我正在查看Godot游戏引擎的源代码,并遇到了以下内容(为简单起见,省略了一些内容):

// popup_menu.cpp

int PopupMenu::_get_mouse_over(double x) const
{
    if (x >= get_size().width)
        return -1;
    // ...
}


// control.cpp

Size2 Control::get_size() const
{
    return data.size_cache;
}

Why is it legal to call the method get_size() without first instantiating an object of type Control and then invoking its member function? 为什么在不先实例化Control类型的对象然后调用其成员函数的情况下调用get_size()方法是合法的? I tried to recreate this behavior in my own file, but it would not compile as I would normally expect: 我试图在我自己的文件中重新创建此行为,但是它不会像我通常期望的那样编译:

class Control
{
public:
    double get_size() const;
};

double Control::get_size() const
{
    return 5.0;
}

class PopupMenu
{
public:
    int _get_mouse_over(double d) const;
};

int PopupMenu::_get_mouse_over(double d) const
{
    return d > get_size(); // compile error, as expected
}

What could be causing this behavior? 是什么导致这种现象? If you are interested, the actual source code for each of these methods can be found at: 如果您有兴趣,可以在以下位置找到每种方法的实际源代码:

line 110: https://github.com/godotengine/godot/blob/master/scene/gui/popup_menu.cpp 第110行: https//github.com/godotengine/godot/blob/master/scene/gui/popup_menu.cpp

line 1770: https://github.com/godotengine/godot/blob/master/scene/gui/control.cpp 1770行: https : //github.com/godotengine/godot/blob/master/scene/gui/control.cpp

I searched for this question and found C#: calling non static member function without creating object which does not answer my question, since in his case there actually was an instance that the method was being invoked through (and it's a different language). 我搜索了这个问题,发现了C#:在不创建无法回答我问题的对象的情况下调用非静态成员函数 ,因为在他的情况下,实际上存在一个实例,该方法是通过方法调用的(这是另一种语言)。

Becuase PopupMenu derives from Control , every instance of PopupMenu is also an instance of Control . 因为PopupMenuControl派生,所以PopupMenu每个实例也是Control一个实例。

When a member function of PopupMenu calls get_size() , it calls Control's get_size() function on itself. PopupMenu的成员函数调用get_size() ,它会自行调用Control的get_size()函数。

Or stated differently, PopupMenu has a get_size() function because it is derived from Control . 换句话说, PopupMenu具有get_size()函数,因为它是从Control派生的。

In your recreation, PopupMenu doesn't derive from Control so this does not apply. 在您的娱乐中, PopupMenu不是从Control派生的,因此不适用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM