为什么编译器没有看到类的完整定义?

时间:2014-11-10 09:44:47

标签: c++

代码:此作品

class smallDOUBLE;

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

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

smallINT::operator smallDOUBLE(){return val;} //Comment this line.

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

但是当我评论smallINT::operator smallDOUBLE(){return val;}时,operator smallDOUBLE();   并取消注释

operator smallDOUBLE(){return val;}编译器抛出错误说

enter image description here

为什么编译器看不到类的完整定义,如果它是前向声明的并且为类的每个成员找到定义,那么程序员不必在外面的某个地方明确定义成员?

什么阻止编译器这样做?

1 个答案:

答案 0 :(得分:3)

在您尝试将某个数字转换为smallDOUBLE时,对该类的了解不会比它是一个类。

对于所有编译器都知道可能没有任何相关的构造函数来完成这项工作。

那么为什么编译器只是将问题打开并在最终遇到smallDOUBLE类定义时填入适当的代码?或者第二次通过源代码?那么,对于一个,该定义可以在不同的转换单元中,这将需要在链接时生成代码,这在今天是闻所未闻的(例如,考虑全局优化),但C和C ++被设计为不需要。这不仅仅是一个技术问题。如果它完成了,那么在链接时间之前你不会得到任何真正的错误信息(哦,我终于发现那里没有合适的构造函数)。

相关问题