超载。 -> 和 :: 用于多平台类

发布于 2024-07-13 11:52:48 字数 411 浏览 7 评论 0原文

假设我有三个窗口类,一个对应于我想要支持的每个操作系统:

  • WindowsWindow
  • OSXWindow
  • LinuxWindow

它们都继承自 Window 类。 这也是您实例化的类。 Window 类有 . -> 和 :: 运算符重载,并且根据运行的操作系统(基于 IFDEF),它将 this 指针强制转换为相关类。

我想做的只是创建一个 Window 实例,而不知道正在运行什么操作系统。 这种想法是不是非常错误呢? 沮丧就危险吗? 有更好的方法来做到这一点吗?

我知道有库可以做到这一点,但我想自己尝试一下。

我想最简单的方法就是创建一个工厂。 但这样的事能做吗?

Say I have three window classes, one for each OS I want to support:

  • WindowsWindow
  • OSXWindow
  • LinuxWindow

They all inherit from the Window class. This is also the class you instantiate.
The Window class have the . -> and :: operators overloaded, and depending on which OS were running on (based on IFDEFs) it casts the this pointer to the relevant class.

What I want to do is just create a Window instance without any clue as to what OS is running. Is this thinking very wrong? Is the downcast to dangerous? Are there better ways to do this?

Im aware that there are libraries to do this, but I want to try it myself.

I guess the easiest way is to create a factory. But can something like this be done?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦太阳 2024-07-20 11:52:48

您根本无法重载作用域解析运算符 :: 。 你可以超载 -> 运算符,但是当您调用该运算符时,您已经必须拥有所需类型的对象。 要创建窗口,只需使用一个简单的工厂方法:

class Window
{
public:
    static Window *CreateWindow(...)
    {
#ifdef _WIN32
        return new Win32Window(...);
#elif defined(/** whatever is defined for Linux */)
        return new X11Window(...);
#elif defined(/** whatever is defined for Mac */)
        return new CocoaWindow(...);
#else
#error "Bad platform!"
#endif
    }
};

You can't overload the scope resolution operator :: at all. You could overload the -> operator, but when you invoke that operator, you already have to have an object of the requisite type. For creating your windows, just use a simple factory method:

class Window
{
public:
    static Window *CreateWindow(...)
    {
#ifdef _WIN32
        return new Win32Window(...);
#elif defined(/** whatever is defined for Linux */)
        return new X11Window(...);
#elif defined(/** whatever is defined for Mac */)
        return new CocoaWindow(...);
#else
#error "Bad platform!"
#endif
    }
};
自在安然 2024-07-20 11:52:48

您可能应该做的是拥有一个工厂方法,并使用 PIMPL 习惯用法。 您的工厂创建 2 个类 - 一个 Window 类和一个 WindowImpl 类。 Window 类只是将方法调用转发给 WindowImpl 类。 客户端代码向工厂请求一个窗口,工厂知道(基于配置、平台检查等)要使用哪个实现类。

What you should probably do is have a factory method, and use the PIMPL idiom. Your factory creates 2 classes - a Window class and a WindowImpl class. The Window class just forwards method calls to the WindowImpl class. The client code asks the factory for a Window, and the factory knows (based on configuration, platform checks, whatever) which implementation class to use.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文