开发者

C++ Problem declaring multiple object instances on the same line

For a homework assignment, I'm having a hard time understanding the behavior when the main class is instantiating two objects of the same class on the same line as follows. Note that the object of the assignment is for the class to behave like an int:

main () {
  MyClass x,y = 5;
  cout << "x = " << x << endl; // outputs x = 0...why not 5???
  cout << "y = " << y << endl; // outputs y = 5
}

and here's header file class definition:

class MyClass {
   public:
      MyClass(int initValue = 0); //constructor
      operator int() {return myValue}; //conversi开发者_StackOverflow中文版on operator to int
   private:
      int myValue;
}

and finally, my source file:

#include "MyClass.h"

MyClass::MyClass(int initValue) {
   myValue = initValue;
}

Why doesn't x get initialized with the value of 5 like y does?


The problem is that C++ is parsing

MyClass x,y = 5;

As if you had written

MyClass x;
MyClass y = 5;

And so x is getting default-initialized rather than initialized with 5. To fix this, change the line to read

MyClass x = 5, y = 5;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜