Why does it work to return an int
in the method B minus
if the method is supposed to return an object of type B
?
#include <iostream>
class B
{
public:
int a;
public:
B(int i=0)
{
a=i;
}
B minus()
{
return (1-a);
}
};
int main()
{
B x(18);
x = x.minus();
std::cout << x.a << '\n';
return 0;
}
A constructor with a single argument is considered a converting constructor . When an argument of type X is needed, and a type Y is given instead, the compiler will look for a converting constructor (or a type conversion operator) from Y to X. In this case it finds one, using your B(int)
constructor. In essence, your return (1-a);
is changed to return B(1-a);
.
As mentioned in several other (also correct) answers, if you do not wish the constructor to be considered a converting constructor, you should preface it with the explicit
keyword.
The line
return (1-a);
calls the implicit conversion constructor
B(int i=0)
{
a=i;
}
So it's the same as writing
return B(1-a);
Note that the copy constructor is still generated, unless you delete
it.
If you want to avoid that, write
explicit B(int i=0)
// ^^^^^^^^
{
a=i;
}
this will actually force a user to write
return B(1-a);
This is happening because single-argument constructor can be used as an implicit cast from argument type to object type.
In your case, you have a constructor which accepts an argument of type int
, so this constructor can be used to convert int
into B
.
To prevent those constructors to be used in conversion, you should mark constructor explicit
- and it's a good practice to do so for all single-argument constructors, since in practice those implicit conversions are more often undesired than desired.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.