简体   繁体   English

为什么以下代码编译

[英]why does the following code compile

#include<iostream>
using namespace std;
class Foo {
void Bar( void ) const ;
};
int main()
{
  Foo f;
  cout<<sizeof(f)<<endl;
}

I ran this on g++,it did not give me any compilation error. 我在g ++上运行它,它没有给我任何编译错误。 Also, it executed giving o/p 1 which is correct. 此外,它执行了给出正确的o / p 1。 But I was expecting, error during linking. 但我期待,链接期间出错。 Is this compiler dependent? 这个编译器是否依赖?

I can only imagine that you expected to get an error as Foo::Bar is not defined. 我只能想象你期望得到一个错误,因为没有定义Foo::Bar The One Definition Rule in the standard requires only that used elements are defined. 标准中的一个定义规则仅要求定义使用的元素。 In your particular case, nothing in your program uses Foo::Bar , so the program does not need that definition. 在您的特定情况下,程序中没有任何内容使用 Foo::Bar ,因此程序不需要该定义。

This will link because there are no outstanding references to Foo::Bar, and there for its definition is not required. 这将链接,因为没有对Foo :: Bar的未完成引用,并且不需要它的定义。 Had you actually tried to make a call such as f.bar() it would have given you the error. 如果你真的试图打电话,如f.bar()它会给你错误。

There is no linker error, because all dependencies are resolved. 没有链接器错误,因为所有依赖项都已解析。

As soon as you call the method Bar() and don't define it, you will get a linker error. 一旦调用方法Bar()并且没有定义它,就会出现链接器错误。 Because then you reference Bar() and the linker cannot resolve it. 因为那时你引用Bar()并且链接器无法解析它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM