开发者

How C++ is this code working?

I have a strange bit of 开发者_运维技巧code. I must have been hitting my keyboard with my eyes closed because this type of thing is really dumb, but weird thing is, I caught it after the program ran successfully.

struct Number{
private:
  unsigned long longNumber;
public:

   Number(unsigned long n)
   {
      longNumber = n;
   }

  unsigned long getReverse()
  {
      /*some magic that returns an unsigned long */
  }

  inline
  unsigned long getLong()
  {
      return longNumber;  
  }
  inline
  static Number add(Number one, Number two)
  {
      return Number(one.getLong() + two.getLong());
  }
};


int main()
{
  scanf("%lu", n);
  Number number = Number(n);
  number = Number::add(number, number.getReverse());
  return 0;
}

There's more stuff going on in main() of course and Number has few more members and functions, but this is what's important I believe.

If you look in main, you'll see that add() is being passed a Number and an unsigned long, but add() only accepts Number and Number.

What's going on here?

EDIT: added constructor above


Since Number has a constructor which accepts unsigned long the compiler is creating a temporary object of type Number from the return value of number.getReverse() and passing it to the add function. If you don't want such implicit conversion to occur, you need to declare the Number constructor as explicit.


You're getting an implicit conversion from long to Number. You're also not showing us all your code or a working segment.


You have left out the constructor that takes a long as an argument.

The second argument to the call: Number::add(number, number.getReverse()) is being converted to a Number temporary.


As others said, it is because you don't have an explicit constructor. For more details on why a constructor should be explicit or not, see this SO question

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜