【问题标题】:conversion operator with forward declartation具有前向声明的转换运算符
【发布时间】:2014-03-18 14:41:05
【问题描述】:

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

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

【问题讨论】:

  • 两个类定义完成后,定义类外的函数。
  • 澄清一下,问题不在于您返回的是 Cow,返回类型不需要在函数声明中定义。问题是您有函数的定义(包括为 Cow、Cow(i) 构造函数、复制/移动构造函数(如果没有省略)分配空间)所有这些都尚未声明。
  • 将牛变成马或反之亦然是个绝招!
  • 你有没有机会给我一个例子来说明你的意思是 MadScienceDreams?

标签: c++ operators overloading conversion-operator


【解决方案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); }

【讨论】:

  • 很好,但是我注意到我只需要对 Horse 应用这个解决方案,Cow 中的操作符就可以了。
  • 是的,你只需要它用于引用它下面的最顶层的类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-17
  • 1970-01-01
  • 2015-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多