一道c题的不同解答方法

方法如下:

  • 用宏替换printf函数
     1 #include <stdio.h>
    2 #include <stdlib.h>
    3 #define printf(s) puts("Begin\n Hello,world!\nEnd")
    4 void hello()
    5 {
    6 printf(" Hello,world!\n");
    7 }
    8 int main()
    9 {
    10 hello();
    11 system("pause");
    12 return 0;
    13 }
  • 用宏替换hello函数
     1 #include <stdio.h>
    2 #include <stdlib.h>
    3 void hello()
    4 {
    5 printf(" Hello,world!\n");
    6 }
    7 void beginhello()
    8 {
    9 printf("Begin\n Hello,world!\nEnd\n");
    10 }
    11 #define hello() beginhello()
    12 int main()
    13 {
    14 hello();
    15 system("pause");
    16 return 0;
    17 }
  • 用函数指针重定向hello函数
     1 #include <stdio.h>
    2 #include <stdlib.h>
    3 #if 0
    4 void hello()
    5 {
    6 printf(" Hello,world!\n");
    7 }
    8 #endif
    9 void beginhello()
    10 {
    11 printf("Begin\n Hello,world!\nEnd\n");
    12 }
    13 void (*hello)() = &beginhello;
    14 int main()
    15 {
    16 hello();
    17 system("pause");
    18 return 0;
    19 }
  • 用宏替换hello函数名
     1 #include <stdio.h>
    2 #include <stdlib.h>
    3 void hello()
    4 {
    5 printf(" Hello,world!\n");
    6 }
    7 void beginhello()
    8 {
    9 printf("Begin\n Hello,world!\nEnd\n");
    10 }
    11 #define hello beginhello
    12 int main()
    13 {
    14 hello();
    15 system("pause");
    16 return 0;
    17 }
  • 在hello函数里面声明一个临时对象,利用对象构造函数和析构函数
     1 #include <cstdlib>
    2 #include <iostream>
    3 using namespace std;
    4 class test
    5 {
    6 public:
    7 test()
    8 {
    9 cout<<"Begin\n";
    10 }
    11 ~test()
    12 {
    13 cout<<"End\n";
    14 }
    15
    16 };
    17 void hello()
    18 {
    19 test t;
    20 printf(" Hello,world!\n");
    21 }
    22 int main()
    23 {
    24 hello();
    25 system("pause");
    26 return 0;
    27 }
  • 在main函数前面定义一个全局变量,利用对象构造函数和析构函数,但是因为加了system("pause"),控制台看不到最后输出的"End",注释掉system("pause")后运行结果是符合题目要求的,虽然一闪而过,我们看不到控制台输出的内容。

     1 #include <cstdlib>
    2 #include <iostream>
    3 using namespace std;
    4 class test
    5 {
    6 public:
    7 test()
    8 {
    9 cout<<"Begin\n";
    10 }
    11 ~test()
    12 {
    13 cout<<"End\n";
    14 }
    15
    16 };
    17 void hello()
    18 {
    19
    20 printf(" Hello,world!\n");
    21 }
    22 test t;
    23 int main()
    24 {
    25 hello();
    26 system("pause");
    27 return 0;
    28 }

    以上程序均在gun c++下编译运行,其他编译器下程序未测试


      

 

posted on 2012-03-18 19:55  tilltheendwjx  阅读(214)  评论(0编辑  收藏  举报

导航