-
February 13th, 2010, 05:46 PM
#1
A question regarding convertion constructor
Here is the code snippet. In the definition of class Rational, I specified convertion constructor explicit so that I can prevent a int converted implicitly into a Rational object. But to my surprise, when I call Rational r = r1*2, 2 is still converted to a Rational object. Why?
Code:
class Rational
{
public:
Rational(int x = 0, int y = 1)
{
num = x;
den = y;
}
explicit Rational(const int& x)
{
}
const Rational& operator*(const Rational& rhs)
{
num*=rhs.num;
den*=rhs.den;
return *this;
}
private:
int num;
int den;
};
int main()
{
Rational r1(2, 3);
Rational r = r1*2;
return 0;
}
-
February 13th, 2010, 05:52 PM
#2
Re: A question regarding convertion constructor
Code:
Rational(int x = 0, int y = 1)
Because of the default value for y that constructor can convert an int to a Rational.
Kurt
-
February 13th, 2010, 06:07 PM
#3
Re: A question regarding convertion constructor
So constructor Rational(int x = 0, int y = 1) could also be a convertion constructor. It is good to learn. Thanks.
Originally Posted by ZuK
Code:
Rational(int x = 0, int y = 1)
Because of the default value for y that constructor can convert an int to a Rational.
Kurt
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|