3

How can I implement typecast operator for a forward declared class. My code is.

class CDB;
class CDM
{
public:
    CDM(int = 0, int = 0);
    operator CDB() const  //error
    {
    }
private:
    int     m_nMeters;
    int     m_nCentimeters;
};

class CDB
{
public:
    CDB(int = 0, int = 0);
    operator CDM() const  //error
    {
    }
private:
    int     m_nFeet;
    int     m_nInches;
};

When I compiled it I got an error

error C2027: use of undefined type 'CDB'

Nidhin MS
  • 229
  • 1
  • 11
  • 1
    The definition of `operator CDB` needs `CDB` to be a complete type. The declaration does not. – chris Aug 25 '14 at 12:24

2 Answers2

7

Just declare the conversion operators. Define them afterwards (after you completely defined the classes). E.G.:

class CDB;
class CDM
{
public:
    CDM(int = 0, int = 0);
    operator CDB() const; // just a declaration
private:
    int     m_nMeters;
    int     m_nCentimeters;
};

class CDB
{
public:
    CDB(int = 0, int = 0);
    operator CDM() const // we're able to define it here already since CDM is already defined completely
    {
        return CDM(5, 5);
    }
private:
    int     m_nFeet;
    int     m_nInches;
};
CDM::operator CDB() const // the definition
{
    return CDB(5, 5);
}
Fytch
  • 1,067
  • 1
  • 6
  • 18
0

You cannot use or call the members of a class that is to be looked ahead. However, conversion can be done in two ways (a) through constructor (b) through cast operator, so here appears a reasonable solution (data types made as float or you may them double, because with int you will lose data)

class CDB;
class CDM
{
    friend class CDB;
public:
    CDM(float a= 0, float b= 0):m_nMeters(a), m_nCentimeters(b){}
/*    operator CDB() const  //error
    {
        return CDB(m_nMeters*0.3048, m_nCentimeters*2.54);
    } */
private:
    float     m_nMeters;
    float     m_nCentimeters;
};

class CDB
{
public:
    CDB(float a= 0, float b= 0):m_nFeet(a), m_nInches(b){}
    CDB(const CDM& acdm) {
        m_nFeet = 3.28084 * acdm.m_nMeters;
        m_nInches = 0.393701 * acdm.m_nCentimeters;
    }
    operator CDM() const 
    {
        return CDM(m_nFeet*0.3048, m_nInches*2.54);
    }
private:
    float     m_nFeet;
    float     m_nInches;
};
Dr. Debasish Jana
  • 6,980
  • 4
  • 30
  • 69