question about class [duplicate]
Possible Duplicates:
Why should I prefer to use member initialization list? C++ - what does the colon after a constructor mean?
here is follo开发者_Go百科wing code
class vector2d {
public:
double x,y;
vector2d (double px,double py): x(px), y(py) {}
i dont understand this line
vector2d (double px,double py): x(px), y(py) {}
is it same as
vector2d(double px,double py){ x=px;y=py;}?
or?
Yes, it's the same in your example. However, there's a subtle difference: x(px) initializes x to px, but x=px assigns it. You'll not know the difference for a double
variable, but if x where a class there would be a big difference. Let's pretend that x is a class of type foo
:
x(px) would call the foo copy constructor, foo::foo(foo &classToCopyFrom).
x=px on the other hand, would first call the foo
default constructor, then it would call the foo
assignment operator.
This is a good reason that you should prefer x(px) in most cases.
精彩评论