如果循环体内存在逻辑判断,并且循环次数很大,宜将逻辑判断移到循环体的外面。
并且由 于前者老要进行逻辑判断,打断了循环“流水线”作业,使得编译器不能对循环进 行优化处理,降低了效率。
如果 N 非常小,两者效率差别并不明显,,因为程序更加简洁。
1 #include <iostream> 2 3 /* run this program using the console pauser or add your own getch, system("pause") or input loop */ 4 using namespace std; 5 //定义最低层基类First,它作为其他类的基类 6 class First { 7 int val1; 8 public: 9 First() { 10 cout<<"The First initialized"<<endl; 11 } 12 ~First() { 13 cout<<"The First destroyed"<<endl; 14 } 15 }; 16 //定义派生类Second,它作为其他类的基类 17 class Second :public First { //默认为private模式 18 int val2; 19 public: 20 Second() { 21 cout<<"The Second initialized"<<endl; 22 } 23 ~Second() { 24 cout<<"The Second destroyed"<<endl; 25 } 26 }; 27 //定义最上层派生类Three 28 class Three :public Second { 29 int val3; 30 public: 31 Three() { 32 cout<<"The Three initialized"<<endl; 33 } 34 ~Three() { 35 cout<<"The Three destroyed"<<endl; 36 } 37 }; 38 //main()函数中测试构造函数和析构函数的执行情况 39 40 int main(int argc, char** argv) { 41 Three t1; 42 cout<<"---- Use the t1----"<<endl; 43 return 0; 44 }