[英]What's the difference between an object created in function call and object passed in
This is obviously a hole in my self taught computer science education... 这显然是我自学计算机科学教育的一个漏洞。
The constructor for a text control (wxTextCtrl) in a wxWidgets application has an optional parameter for a validator object. wxWidgets应用程序中的文本控件(wxTextCtrl)的构造函数具有一个用于验证器对象的可选参数。 All of the code examples create the validator on the fly within the constructor for the text control. 所有代码示例都在文本控件的构造函数中动态创建验证器。
This works.. 这有效..
wxString value = L"0.0";
wxTextCtrl* _Text = new wxTextCtrl(this, wxID_ANY, value,
wxDefaultPosition, wxDefaultSize, 0,
wxTextValidator(wxFILTER_NUMERIC, &value));
However in my particular case I want to create the validator in another function and pass it back, which isn't working. 但是,在我的特定情况下,我想在另一个函数中创建验证器并将其传递回去,这是行不通的。 As an intermediate step I've tried to create it just before creating the wxTextCtrl and pass it in but that doesn't work either... 作为一个中间步骤,我尝试在创建wxTextCtrl并将其传递之前创建它,但这也不起作用...
wxString value = L"0.0";
wxValidator valid = wxTextValidator(wxFILTER_NUMERIC, &value);
wxTextCtrl* _Text = new wxTextCtrl(this, wxID_ANY, value,
wxDefaultPosition, wxDefaultSize, 0, valid);
Although this compiles and runs it doesn't perform the validation. 尽管这会编译并运行,但不会执行验证。 Can anyone explain why? 谁能解释为什么?
The prototype for the wxTextValidator calls for a constant reference.. wxTextValidator的原型需要一个常量引用。
wxTextCtrl::wxTextCtrl ( wxWindow * parent,
wxWindowID id,
const wxString & value = wxEmptyString,
const wxPoint & pos = wxDefaultPosition,
const wxSize & size = wxDefaultSize,
long style = 0,
const wxValidator & validator = wxDefaultValidator,
const wxString & name = wxTextCtrlNameStr
)
You have sliced the wxTextValidator
object when you assigned it to a variable of type wxValidator
, its base class. 将wxTextValidator
对象分配给其基类wxValidator
类型的变量时,已对它进行了切片 。 To fix this, you'll need to preserve the more specific type: 要解决此问题,您需要保留更具体的类型:
wxTextValidator valid = wxTextValidator(wxFILTER_NUMERIC, &value);
You can use auto
to avoid repeating yourself. 您可以使用auto
来避免重复自己。
Alternatively, you can use lifetime extension which occurs when assigning a temporary to a const
reference: 另外,您可以使用生命周期扩展 ,这是在将临时const
分配给const
引用时发生的:
const wxValidator& valid = wxTextValidator(wxFILTER_NUMERIC, &value);
This works because there is no copy, and therefore no slicing. 之所以有效,是因为没有副本,因此也没有切片。
Note that when designing your own classes, it's often a good idea to prevent object slicing by making your base classes abstract, or making their (copy) constructors protected
. 请注意,在设计自己的类时,通过使基类抽象化或使它们的(副本)构造函数protected
来防止对象切片通常是一个好主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.