C ++:为事件处理程序创建一个匿名类 [英] C++: Create an anonymous class for event handlers
问题描述
免责声明:此说明包含大量Qt详细信息。他们不必回答这个问题,我只是想给你背景。
Disclaimer: This description contains a lot of Qt specifics. They are not necessary to answer the question, I just wanted to give you the background.
我需要对 focusInEvent
of a QTextEdit
。
不幸的是,这不是一个信号,这就是为什么我需要子类 QTextEdit
。由于这是我需要的唯一变化,我想使用一个匿名子类
I need to react on the focusInEvent
of a QTextEdit
.
Unfortunately this is not available as a signal, that's why I need to subclass QTextEdit
. Since this is the only change I need, I would like to use an anonymous subclass
像这样:
myTextEdit =new QTextEdit(){
void focusInEvent(){
//code here
}
};
这是我将用Java编写的代码,它不能在c ++中编译。
下面的所有代码都在自定义 QWidget
的构造函数中。 QTextEdit
包含在此小部件中,应在其构造函数中初始化。
This is the code I would write in Java, it doesn't compile in c++.
All following code is within the constructor of a custom QWidget
. The QTextEdit
is contained in this widget and should be initialized in its constructor.
奇怪的是,此代码编译:
Strangely this code compiles:
class MyTextEdit:protected QTextEdit{
void focusInEvent();
};
auto myTextEdit=new MyTextEdit();
但是没有用,因为我不能分配一个 myTextEdit *
指向 QTextEdit
的指针。不知何故多态性失败。这段代码不编译:
but is useless, since I can't assign an instance of myTextEdit*
to a pointer to QTextEdit
. Somehow polymorphism fails. This code doesn't compile:
class MyTextEdit:protected QTextEdit{
void focusInEvent();
};
QTextEdit* myTextEdit=new MyTextEdit();
编译器错误是:
/home/lars/ProgrammierPraktikum/moleculator/implementation/Moleculator/gui_elements/editor.cpp:40:
错误:'QTextEdit'是
的无法访问的基础Editor :: Editor (std :: shared_ptr):: MyTextEdit'
QTextEdit * myTextEdit = new MyTextEdit();
/home/lars/ProgrammierPraktikum/moleculator/implementation/Moleculator/gui_elements/editor.cpp:40: error: 'QTextEdit' is an inaccessible base of 'Editor::Editor(std::shared_ptr)::MyTextEdit' QTextEdit* myTextEdit=new MyTextEdit();
问题:
Actual question:
如何创建一个与其超类指针兼容的匿名子类?
How do I create an anonymous subclass that is compatible to pointers of its superclass ?
推荐答案
您的子类化尝试
class MyTextEdit:protected QTextEdit{
void focusInEvent();
};
QTextEdit* myTextEdit=new MyTextEdit();
几乎可以。
只是因为方法受保护并不意味着您应该继承protected。
Just because the method is protected doesn't mean you should inherit with protected.
- 受保护的方法说:这不是我的界面的一部分。没有人,但我应该能够调用这个。我会自己调用这个(作为事件处理的一部分)。
- 继承protected说:没有人应该知道这个继承,它是一个实现细节,可能对扩展我的类有用。
您希望定期公开继承。
You want the regular public inheritance.
class MyTextEdit:public QTextEdit{
void focusInEvent();
};
QTextEdit* myTextEdit=new MyTextEdit();
现在你说MyTextEdit是QTextEdit的替代品。
您可能需要添加一个构造函数以将父窗口部件提供给MyTextEdit。
Now you are saying that MyTextEdit is a replacement for a QTextEdit. You might want to add a constructor to supply the parent widget to MyTextEdit.
在c ++中没有类似java的匿名内部类。
There is no such thing as a java-like anonymous inner class in c++.
这篇关于C ++:为事件处理程序创建一个匿名类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!