0

我正在尝试使用 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;
};

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

4

1 回答 1

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); }
于 2014-03-18T16:27:24.220 回答