在纸上阅读C++代码,你会怎么做?

eve*_*veo 8 c++

在我的编程课程中,我们根据代码示例进行测试和测验,我们必须完成这些测试和测验并确定最终输出.通常它们是棘手的代码片段,当我意识到,我陷入了一些随机函数,并且不知道我在做什么.

你如何在纸上正确运行代码?跟踪循环,变量,函数,一切,这让我很困惑.

例如,这是我们过去的一个测验,我得到了100%的测试,但是我花了很长时间并且非常混乱:

#include <iostream>
#include <cstring>
using namespace std;

class foo {
     char word[20];
     int qty;

public:
     foo( ) { set(3, 5); }

     foo( int m, const char * s) { set(m, m+1);
                                   strcpy(word, s);       }

     foo(  const foo& a ) { cout << "... hahaha.1" << endl;
                qty = 3 + a.qty;
                strcpy( word, a.word );
                strcat( word, ".5.6.7" );
                cout << "... hahah.2" << endl;  }

     ~foo( ) { cout << qty << "," << word << "!!!" << endl; }

     void set(int a, int b){ qty = a + b;
                             strcpy( word, "summer" ); }
     void wow();

     void output(){ cout << word << "," << qty << endl;  }
};

void hello( foo& );
void greet( foo );

int main() {

     foo x, y(100, "QUIZ");

     greet( y );
     cout << "a.b.c.d.e." << endl;

     hello( x );
     x.output();
     y.output();

     cout << "...the end" << endl;
     return 0;
}

void foo::wow() { strcat(word,".1.2.3");
                  qty += 4;     }

void greet( foo g ) { cout << "...HI.1\n";
                      g.wow(); 
                      g.output(); 
                      cout << "...HI.2\n"; }


void hello(foo & h) {  cout << "...hello.1" << endl;
                foo e;

                e = h;
                h.wow();
                h.output();
                e.output();
                cout << "...hello.2\n"; }
Run Code Online (Sandbox Code Playgroud)

Dco*_*tez 0

实践是理解代码的最好方法。当我尝试进行这样的练习时,我并不是一开始就试图理解所有功能。我从 main 开始,就像调试器一样逐行观察所有变量。如果某件事让你感到困惑,只需将所有变量写在纸上并标记它们的每一个变化。然而,没有什么比训练更好更快地学习阅读和理解代码了。