What arguments must I pass to a function to perform an implicit construction of an object?
My apologies if this is a dupe. I found a number of posts re. preventing implicit conversions, but nothing re. encouraging implicit constructions.
开发者_C百科If I have:
class Rect
{
public:
Rect( float x1, float y1, float x2, float y2){};
};
and the free function:
Rect Scale( const Rect & );
why would
Rect s = Scale( 137.0f, 68.0f, 235.0f, 156.0f );
not do an implicit construction of a const Rect&
and instead generate this compiler error
'Scale' : function does not take 4 arguments
Because the language does not support this feature. You have to write
Rect s = Scale(Rect(137.0f, 68.0f, 235.0f, 156.0f));
"Conversions" in C++ are between objects of one type and another type. You have 4 objects (all of type float), so you could have 4 conversions to 4 other types. There's no way to convert (in the C++ sense of the word) 4 objects to one object.
An implicit conversion via constructor takes place if and only if the constructor takes exactly 1 argument and isn't declared explicit. In this case it takes 4, thus the result.
I think you're talking about implicitly constructing an object. For instance,
class IntWrapper {
public:
IntWrapper(int x) { }
};
void DoSomething( const IntWrapper& ) { }
int main() {
DoSomething(5);
}
This works because IntWrapper
's constructor takes only one argument. In your case, Rect
needs 4 arguments, so there's no implicit construction.
精彩评论