C++ 如何在不显式强制转换的情况下降级函数调用中的类实例
C++ How can I degrade a class instance in a function call without explicitly casting?
我想创建一个管理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
指针,使代码更易于理解、阅读和维护。
相关文章:
- 在没有太多条件句的情况下,我如何避免被零除
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 在未初始化映射的情况下,将值插入到映射的映射中
- 是默认情况下分配给char数组常量的值
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 如何在不产生任何垃圾的情况下获得C中的像素
- 在已经使用Git的情况下减少编译时间
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- 如何在没有信号的情况下从C++执行QML插槽
- 如何在不知道向量大小的情况下输入向量内部的向量?
- 为什么在某些情况下不写入此文件?
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 在没有Xcode的情况下在Mac捆绑包中嵌入框架
- UE4-如何在给定4个屏幕坐标的情况下缩放纹理或材质
- 为什么需要复制构造函数,在哪些情况下它们非常有用
- 在C++中如何在没有pow的情况下进行基础计算
- 松弛原子与无同步情况下的记忆连贯性
- C++ 如何在不显式强制转换的情况下降级函数调用中的类实例
- 如何在不降级为基类的情况下生成*对象的向量
- 如何*首先*获得独占锁,然后在不释放锁的情况下降级为共享锁