在我的编程课上,我们有基于代码示例的测试和测验,我们必须经过并确定最终输出。通常他们是棘手的代码片段,当我意识到时,我被困在一些随机函数中,不知道我在做什么。在纸上走过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"; }
很难知道该说什么超越“读它,理解它。” – 2013-03-24 23:20:21
练习,练习,练习... – jalf 2013-03-24 23:20:30
做笔记,直接对部分代码进行注释,将代码拆分成小块,绘制调用树/图,绘制状态机,展开/折叠调用树/图的细节级别,以便您可以看到相关,不能看到什么不是。跟踪你的进度,这样你就不会陷入无止境的循环,自己一遍又一遍地重复同样的工作。 :)是的,练习,练习和练习。 – 2013-03-24 23:24:37