CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Mar 2004
    Posts
    235

    convert int to class

    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!
    01101000011001010110110001101100011011110010000001110011011001010111100001111001

  2. #2
    Join Date
    Apr 2004
    Location
    Canada
    Posts
    1,342

    Re: convert int to class

    It's possible. All you need to do is give class C a constructor that takes an int argument:

    Code:
    class C
    {
    public:
        C(int i)
        {
             // implementation
        }
        ...
    };
    Then you can write code like this:

    Code:
    int main()
    {
        C a;
        a = C(1)/a;
        return 0;
    }
    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.
    Old Unix programmers never die, they just mv to /dev/null

  3. #3
    Join Date
    May 2000
    Location
    Scotland, Livingston.
    Posts
    728

    Re: convert int to class

    Code:
    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); }
    expressions of the form "a = C(1)/a"; are made possible by the constructor which allows IMPLICIT conversions between ints and C's

    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; }
    Dave Mclelland.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured