-5
....
void foo()
{}
...
foo(); //why we can not call the function here?

int main(int argc, char** argv)
{}

我知道你不能这样做,它会导致编译器错误。我想这可能与一些编译器理论有关,但是任何人都可以告诉我这是什么性质,还是只是一个任意规则?

当我尝试编译以下代码时:

#include<iostream>
using namespace std;   

void foo()
{
    cout<<"test"<<endl;
}   

foo();    

int main() {}

我收到此错误消息。

test.cpp:10:6: 错误: ';' 之前的预期构造函数、析构函数或类型转换 令牌

为什么我会收到此错误?

4

1 回答 1

0

你的假设是错误的。

#include <iostream>
int foo() {
  std::cout << "outside main" << std::endl;
  return 0;
}
int Global = foo();

int main() {
  std::cout << "intside main" << std::endl;
  return 0;
}

现在正式规则:函数调用是一个表达式。表达式可能出现在语句中,语句可能出现在函数中。但是表达式也可能出现在其他上下文中,例如int Global上面的全局对象的初始化。

于 2013-02-04T09:53:55.467 回答