运算符T(){} - 不工作

时间:2014-11-06 12:57:20

标签: c++ operator-overloading

我有一个代码

class smallDOUBLE;

class smallINT
{
private:
    int val;   
public:
   smallINT():val(0){}
   smallINT(int i):val(i){}
   operator smallDOUBLE() {return val;}
};

class smallDOUBLE
{
private:
    double val;
public:
   smallDOUBLE():val(0){}
   smallDOUBLE(double i):val(i){}
   operator smallINT() { return val;}
};

int main()
{
    smallINT int1(10);
    smallDOUBLE DBL1(123.22);
    smallINT int2 = DBL1;
    smallDOUBLE DBL2 = int1;
}

这里的smallINT int2 = DBL1;主要工作正常,但smallDOUBLE DBL2 = int1;会抛出错误说

  

返回类型smallDOUBLE不完整

编译期间

为什么operator smallINT() { return val;}有效

operator smallDOUBLE() {return val;}没有?

enter image description here

2 个答案:

答案 0 :(得分:3)

您收到该错误,因为强制转换操作符返回类型无法使用不完整类型。要解决此问题,您可以声明但不定义,直到定义了另一个类

class smallDOUBLE;

class smallINT
{
private:
    int val;
public:
    smallINT() :val(0){}
    smallINT(int i) :val(i){}
    operator smallDOUBLE();
};

class smallDOUBLE
{
private:
    double val;
public:
    smallDOUBLE() :val(0){}
    smallDOUBLE(double i) :val(i){}
    operator smallINT() { return val; }
};

smallINT::operator smallDOUBLE() { return val; }

Live Example

答案 1 :(得分:3)

错误告诉:为了实现转换功能,您需要将函数转换为的类型已经实现。在类operator smallDOUBLE()的定义之后移动smallDOUBLE的定义会产生可编译的程序。

class smallDOUBLE;

class smallINT
{
private:
int val;   
public:
   smallINT():val(0){}
   smallINT(int i):val(i){}
  operator smallDOUBLE();
};

class smallDOUBLE
{
private:
double val;
public:
   smallDOUBLE():val(0){}
   smallDOUBLE(double i):val(i){}
   // smallINT already defined, no problem here...
   operator smallINT() { return val;}
};

// now that smallDOUBLE is defined...
smallINT::operator smallDOUBLE(){return val;}

int main()
{
  smallINT int1(10);
  smallDOUBLE DBL1(123.22);
  smallINT int2 = DBL1;
  smallDOUBLE DBL2 = int1;
}