I'm going around the internetgo
I saw the C++ code below
What does this explicit
do for you?
class String {
public:
explicit String (int n); //allocate n bytes
String(const char *p); // initialize sobject with string p
};
The C++ compiler can change the value that comes into the function's factor to suit its type. I'll explain what this means in the following example.
class Foo{
public:
int m_foo;
Foo (int foo) : m_foo (foo) {}
};
void printM_foo (Foo foo){
cout << foo.m_foo << endl;
}
int main (){
int num = 43;
printM_foo(num);
}
Result: 43
printM_foo(Foofoo)
receives the foo
type parameter foo
and outputs foo.m_foo
.
However, main()
is now passing the int
type parameter, not the Foo
type.
It even prints well.
How does a compiler work to produce this result?
When printM_foo(num)
is invoked,
The compiler calls the constructor that receives int
as a parameter in the Foo
class
printM_foo(Foooo)
Transform the type to Foo
which is the appropriate parameter type.
The explicit
keyword is used in this situation.
If the use is not intended for automatic conversion, it can cause a bug
Use the explicit
keyword to prevent bugs by preventing the compiler from calling the constructor for parameter type conversion.
Therefore, if you specify explicit
in front of the constructor of the above code as follows,
explicit Foo (int foo) : m_foo (foo) {}
printM_foo(num);
The compiler displays an error
From here on, the parameter type conversion should be done by the programmer, not by the compiler.
class Foo{
public:
int m_foo;
explicit Foo (int foo) : m_foo (foo) {}
};
void printM_foo (Foo foo){
cout << foo.m_foo << endl;
}
int main (){
int num = 43;
printM_foo(num); // Error
}
If you get 43 as a factor in the void printM_Foo (Foooo) declaration, Foo foo = 43 Isn't a temporary object created when it becomes Foofoo (43)
572 Understanding How to Configure Google API Key
567 Who developed the "avformat-59.dll" that comes with FFmpeg?
606 Uncaught (inpromise) Error on Electron: An object could not be cloned
567 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
884 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
© 2024 OneMinuteCode. All rights reserved.