超载。 -> 和 :: 用于多平台类
假设我有三个窗口类,一个对应于我想要支持的每个操作系统:
- 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您根本无法重载作用域解析运算符 :: 。 你可以超载 -> 运算符,但是当您调用该运算符时,您已经必须拥有所需类型的对象。 要创建窗口,只需使用一个简单的工厂方法:
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:
您可能应该做的是拥有一个工厂方法,并使用 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.