带前向声明的转换运算符

时间:2014-03-18 14:41:05

标签: c++ operators overloading conversion-operator

我试图在c ++中使用转换运算符我有2个类,我试图从一个转换为另一个,我收到错误:

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

谁能告诉我我做错了什么?

1 个答案:

答案 0 :(得分:1)

试试这个:

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