Type for type undefined

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

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 the error

error C2027: Using undefined type 'CDB'

+3


source to share


2 answers


Just declare conversion operators. Define them later (after you have fully defined the classes). For example:.



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);
}

      

+7


source


You cannot use or invoke members of the class to be considered. However, the conversion can be done in two ways (a) through the constructor (b) through the translation operator, so a reasonable solution appears here (data types made as float, or you can double them, 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;
};

      

0


source







All Articles