为什么函数只能在其他函数内部调用
Why can functions only be called inside other functions?
....
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:错误:在";"令牌之前进行预期的构造函数、析构函数或类型转换
为什么我会收到此错误?
你的假设是错误的。
#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
上面。
相关文章:
- 在函数内部的声明中初始化数组,并在外部使用它
- 使用C链接在函数内部创建C++模板
- 指针没有更新它在void函数内部指向的值
- SDL_PollEvent() 无法捕获类函数内部SDL_QUIT?
- 为什么从另一个构造函数内部调用C++构造函数不修改类变量?
- WriteProcessMemory 在函数内部失败
- 如何在C++中传递lambda函数内部的对象实例
- 在析构函数内部处理异常(但不抛出)
- 在函数内部传递字符 *str
- 仅在函数内部构建对象时EXC_BAD_ACCESS
- 是否可以使用类的析构函数内部函数来重置值?
- 如何在函数内部使用 zmq(以非阻塞方式)在客户端请求时获取函数的状态?
- 在函数内部错误定位后,从函数中释放返回的指针会导致芯片崩溃
- 我如何从循环内部使用迭代器的函数内部的getter中检索特定的成员
- C++ 修改函数内部的字符
- 从对象成员函数内部删除操作的技术 /设计模式
- C++14 使用捕获说明符递增 lambda 函数内部的值
- 在成员函数内部调用成员函数
- 如何在类构造函数内部对同一类的成员函数启动pthread
- Arduino C++:F()宏在函数内部有意义吗