I have a class
class C
{};
how may I make it possible to do something like this
int main()
{
C a;
a = (C)1/a;
return 0;
}
the "(C)1" I have trouble with.
Thanks in advance!
Printable View
I have a class
class C
{};
how may I make it possible to do something like this
int main()
{
C a;
a = (C)1/a;
return 0;
}
the "(C)1" I have trouble with.
Thanks in advance!
It's possible. All you need to do is give class C a constructor that takes an int argument:
Then you can write code like this:Code:class C
{
public:
C(int i)
{
// implementation
}
...
};
Note that C(1) and (C)1 are effectively the same, however I prefer using C(1) because it makes it clear that you are calling C's constructor.Code:int main()
{
C a;
a = C(1)/a;
return 0;
}
expressions of the form "a = C(1)/a"; are made possible by the constructor which allows IMPLICIT conversions between ints and C'sCode:class C {
public:
C(int i) { m_i = i; }
C& operator=(const C& rhs) { m_i = rhs.m_i; return *this;}
C& operator/(const C& rhs) { m_i /= rhs.m_i; return *this; }
friend C operator/(const C& lhs, const C& rhs);
private:
int m_i;
};
C operator/(const C& lhs, const C& rhs) { return C(lhs.m_i / rhs.m_i); }
The second form "a = 1 / a"; is made possible by the global operator/ (the friend of C) and the constructor.
Whether its wise to use this type of implicit type conversion is another question.
if you only wish to use the first form of the expression declare the constructor as explicit. This means that you forbid the compiler to use if for the purposes of implicit type conversion - but you can still use it as normal.
Code:explicit C(int i) { m_i = i; }