I saw this key word "explicit" in some example code. what does it mean in QT?
Thanks!
I saw this key word "explicit" in some example code. what does it mean in QT?
Thanks!
explicit keywoard is used to avoid implicit type conversion.
Thanks!
Could you please give an example?
example 1 (implicit conversion)
example 2 (using explicit keyword)Qt Code:
class MyObj { public: MyObj(int size): m_size(size) {} private: int m_size; }; .... void A::someMethod() { MyObj mw(10); mw = 5;// wrong; trying convert 5 to MyObj (implicit conversion) }To copy to clipboard, switch view to plain text mode
Qt Code:
class MyObj { public: explicit MyObj(int size): m_size(size) {} private: int m_size; }; .... void A::someMethod() { MyObj mw(10); mw = 5;//compile error; explicit conversion is needed. mw = MyObj(5);//ok }To copy to clipboard, switch view to plain text mode
In another words, if you construct an object and there is no constructor that takes exactly the same types as you are trying to pass, the compiler tries to find conversions from the types you pass to the types there is a constructor for available. The "explicit" keyword prevents that mechanism.
For example if you have a constructor that takes an integer and you try to pass a double to it, the compiler will do an implicit conversion from double to int and will use the constructor taking an int. If you make that constructor explicit, the compiler will not try to convert your double to int but instead will throw an error.
Sorry to contradict, but not really.
The explicit means that if class X has a constructor explicit X(T t) for some type T and you call a function that takes an X, but you pass only a T, then this X will not be implicitly constructed from the given T. (The assignment operator being one example of such a function.)
The example given by spirit illustrates this: you must explicitly construct an instance of X, it will not implicitly convert a constructor's argument (of type T) to an X.
(Side note: it follows that explicit makes only sense for constructors with one argument, as the others can not be used implicitly anyway.)
Yes, you're right. It simply means you have to call the constructor explicitely as a constructor for the item to be constructed, regardless of the types used. My bad.
Bookmarks