C++ 如何在不显式强制转换的情况下降级函数调用中的类实例

C++ How can I degrade a class instance in a function call without explicitly casting?

本文关键字:降级 情况下 函数调用 实例 转换 C++      更新时间:2023-10-16

我想创建一个管理SDL_Window指针的 Window 类,并且访问用于函数调用的SDL_Window指针非常简单,只需使用 Window 类实例并让转换运算符充当"getter"。喜欢这个:

Window win("some name",10,10,100,100,Flags);
SDL_DoSthWithWin(win,10.0f); //SDL_DoSthWithWin uses SDL_Window* but its converted.

我目前的尝试看起来(有点(像这样:

class Window{
private:
    //Irrelevant
    SDL_Window *window; //SDL Type for handling Windows. Always a pointer
    static Window *ActiveWindow //Pointer to the active Window.
    //More irrelevant stuff
public:
    static Window& getActive(); //this returns a reference to the active obj
    Window(someParms);
    explicit operator SDL_Window* (){return this->window;}; //This conversion operator should do the trick?
    //More irrelevant stuff really
}

但是,结果是,由于某种原因,如果不像这样显式转换,它就不起作用:

SDL_DoSthWithWin((SDL_Window*)win,---);

如果只有制作转换运算符的全部目的是保存写入".getWindow(("所需的字母,那就太好

好吧,我怎样才能(正确地(做到这一点,这样我就不必投射了。

好吧,你确实说转换运算符是explicit .这意味着您实际上必须明确说明该转换。

我应该补充一点,这通常是一个糟糕的选择,拥有这样的隐式转换运算符。必须显式并使用getWindow(或类似名称的函数(来获取SDL_Window指针,使代码更易于理解、阅读和维护。