开发者

question about class [duplicate]

This question already has answers here: Closed 12 years ago.

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 doublevariable, 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜