Question

I'm trying to work with conversion operators in c++ I have 2 classes that I'm trying to convert from one to the other, and I am getting errors:

class Cow; //error: forward declaration of 'struct Cow'

class Horse {
public:
    Horse():i(0){}
    Horse(int i):i(i){}
    operator Cow() const { return Cow(i); } // error: invalid use of incomplete type 'struct Cow'
                                            //error : return type 'struct Cow' is incomplete

private:
    int i;
};

class Cow{
public:
    Cow():i(0){}
    Cow(int i):i(i){}
    operator Horse() const { return Horse(i); }
private:
    int i;
};

Can anyone tell me what I'm doing wrong?

Was it helpful?

Solution

Try this:

class Cow;

class Horse {
public:
    Horse():i(0){}
    Horse(int i):i(i){}
    operator Cow() const;                     
private:
    int i;
};

class Cow{
public:
    Cow():i(0){}
    Cow(int i):i(i){}
    operator Horse() const;
private:
    int i;
};

Horse::operator Cow() const { return Cow(i); }                                      
Cow::operator Horse() const { return Horse(i); }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top