stroustrup ppp第8章钻头头部

stroustrup ppp chapter 8 drill headers

本文关键字:头部 8章 ppp stroustrup      更新时间:2023-10-16

对于那些已经阅读并完成了stroustrup的";用c++编写程序的原理与实践;我在做第8章练习的第一部分时遇到了麻烦。我对这一部分的主要问题是在问题的末尾;在Windows上,您需要在项目中同时使用use.cppmy.cpp,并在usiness.cpp中使用{char-cc;cin>>cc;}才能看到您的输出"如果我们不允许std_lib_facilities.h使用.cpp,我们如何实现这一点
当它说";在Windows上,您需要在一个项目中同时使用use.cppmy.cpp"?如果我想深入了解此事,请告诉我。

创建三个文件:my.hmy.cpp使用.cpp头文件my.hTR

extern int foo
清空print_foo()
作废打印(int)

源代码文件my.cpp#包含my.hstd_lib_facilities.h,定义print_foo()使用cout打印foo的值,以及print(int i)out打印i的值

源代码文件使用.cpp,该文件将#includemy.h、定义main()foo的值设置为7并使用print_foo()打印,以及使用print()打印值99。请注意,use.cpp不包括std_lib_facilities.h,因为它不直接使用任何这些设施

编译这些文件并运行。在Windows上,您需要在项目中同时使用use.cppmy.cpp,并在usiness.cpp中使用{char-cc;cin>>cc;}才能看到您的输出

{ char cc; cin>>cc; }

用于从标准输入中读取字符(等待输入)。在VS和其他IDE中,您需要这样做只是为了查看程序的输出,否则cmd窗口将关闭得太快而无法读取输出。您不需要std_lib_facilities.h,只需要include <iostream>,并在main函数的末尾编写上面的代码。

编译这些文件并运行。在Windows上,两者都需要在项目中使用.cpp和my.cpp,并在中使用{char-cc;cin>>cc;}使用.cpp可以查看您的输出。

要在windows、VS或其他IDE中进行编译,需要同时包含这两个源文件。在linux上,你也需要两者,然而,编译过程(makefile或g++)明确要求这些文件,所以对于windows,这些文件是被强调的。

我随后解决了上面代码中的错误。变量foo需要在my.h头文件中声明为extern,并在use.cpp文件中的main()之前再次声明,如下所示。问题的本质是没有一个教科书所反对的全局变量。但这种使用全局变量的解决方案才是有效的。

//
    use.cpp
    
    #include"my.h"
    #include<iostream>
    using namespace std;
    
    extern int foo = 7;
    
    void delimiter() {
        cout << " ============================================================n";
        }
    
    int main () {
        int i = 1;
        delimiter();
        cout << " Using print_foo() to print foo which is initialized as an" << endl;
        cout << " external global variable = 7." << endl << " --> ";
        print_foo();  //7
        cout << endl;
        delimiter();
        cout << " Print the variable i = 1 using print(i)." << endl << " --> ";
        print(i);  //1
        cout << endl;
        delimiter();
        cout << " Print the value 99 using print()." << endl << " --> ";
        print(99);  //99
        cout << endl;
        delimiter();
        cout << " Print the global variable foo using print()." << endl << " --> ";
        print(foo);  //7
        cout << endl;
        cout << "  Enter any character to quit." << " -- > ";
        char cc; cin >> cc;
        return 0;
    }
//
my.cpp then becomes simply
//
    #include"my.h"
    #include"std_lib_facilities.h"
    
    void print(int i) {
        cout << i;
    }
    
    void print_foo() {
        cout << foo;
    }
//
and finally my.h is:
//
    extern int foo;
    void print_foo();
    void print(int);
//