使用g+的输出错误+;在linux和windows上进行更正 我正在学习C++,决定写一个小程序来在可变范围内实践。问题是,在编译和执行之后,我在Linux上得到了不同的(我认为是错误的)输出,而在windows上,一切都是正确的。代码如下: /*main.cpp*/ #include <iostream> using namespace std; extern int x; int f(); int main() { cout << " x = " << x << endl; cout << "1st output of f() " << f() << endl; cout << "2nd output of f() " << f() << endl; return 0; } /*f.cpp*/ #include<iostream> using namespace std; int x = 10000; int f() { static int x = ::x; { static int x = 8; cout << x++ << endl; } cout << x++ << endl; return x; } int main() { cout << " x = " << x << endl; int temp=f(); cout << "1st output of f() " << temp << endl; temp=f(); cout << "2nd output of f() " << temp << endl; return 0; }

使用g+的输出错误+;在linux和windows上进行更正 我正在学习C++,决定写一个小程序来在可变范围内实践。问题是,在编译和执行之后,我在Linux上得到了不同的(我认为是错误的)输出,而在windows上,一切都是正确的。代码如下: /*main.cpp*/ #include <iostream> using namespace std; extern int x; int f(); int main() { cout << " x = " << x << endl; cout << "1st output of f() " << f() << endl; cout << "2nd output of f() " << f() << endl; return 0; } /*f.cpp*/ #include<iostream> using namespace std; int x = 10000; int f() { static int x = ::x; { static int x = 8; cout << x++ << endl; } cout << x++ << endl; return x; } int main() { cout << " x = " << x << endl; int temp=f(); cout << "1st output of f() " << temp << endl; temp=f(); cout << "2nd output of f() " << temp << endl; return 0; },c++,linux,windows,g++,C++,Linux,Windows,G++,给定(Linux)输出: 据我所知,Linux程序似乎跳过了int f()函数的范围,知道为什么会发生这样的事情吗?在得到评论的帮助后,我明白问题与代码在不同编译器中的执行方式有关,我通过显式调用函数f(),首先执行它的命令,解决了“bug”,然后获取返回值。我尽可能地解释了它,因此下面是代码: /*main.cpp*/ #include <iostream> using namespace std; extern int x; int f(); int main() {

给定(Linux)输出:


据我所知,Linux程序似乎跳过了int f()函数的范围,知道为什么会发生这样的事情吗?

在得到评论的帮助后,我明白问题与代码在不同编译器中的执行方式有关,我通过显式调用函数f(),首先执行它的命令,解决了“bug”,然后获取返回值。我尽可能地解释了它,因此下面是代码:

/*main.cpp*/
#include <iostream> 
using namespace std;

extern int x;
int f();

int main() { 
    cout << " x = " << x << endl; 
    cout << "1st output of f() " << f() << endl;
    cout << "2nd output of f() " << f() << endl;

    return 0;
}



/*f.cpp*/
#include<iostream>
using namespace std;

int x = 10000;
int f() {
    static int x = ::x; 
    {
        static int x = 8;
        cout << x++ << endl; 
    }
    cout << x++ << endl; return x;
}
int main() { 
    cout << " x = " << x << endl; 
    int temp=f();
    cout << "1st output of f() " << temp << endl;
    temp=f();
    cout << "2nd output of f() " << temp << endl;

    return 0;
} 
int main(){

无法复制,因为您可以看到没有跳过任何内容,只有“…f()的输出”部分在不同的时间输出。请记住,所有运算符重载都是作为函数和函数调用实现的。当您使用例如
谢谢大家,我现在明白了。问题在于函数f()的执行顺序;请将答案放在答案栏中。稍后,您可以接受自己的答案。另请参阅