首先谈一下这一讲的主要内容。

  • 单独编译
  • 存储连续性、作用域和链接性
  • 定位new运算符

为何要讲这块知识??C++为在内存中存储数据方面提供了多种选择。通常大型程序都由多个源代码文件组成,这些文件可能共享一些数据。这样的程序涉及到程序文件的单独编译,这些我们都要学习。

 

【单独编译】

我们常常将组件函数放在独立的文件中。

之前我们学习到,可以单独编译这些文件,然后将它们链接成可执行的程序。(通常,C++编译器既编译程序,也管理链接器。)如果只修改了一个文件,则可以只重新编译该文件,然后将它与其他文件的编译版本链接。这使得管理大程序更便捷。

此外,大多数C++环境都提供了其他工具来帮助管理。例如,UNIX和Linux系统都具有make程序,可以跟踪程序依赖的文件以及这些文件的最后修改时间。运行make时,如果它检测到上次编译后修改了源文件,make将记住重新构建程序所需的步骤。大多数集成开发环境(包括Microsoft Visual C++、Apple Xcode和Freescale CodeWarrior)都在Project菜单中提供了类似的工具。

 

现在我们来看一个简单的示例。我们不是要从中了解编译的细节(这取决于实现),而是要重点介绍更通用的方面,如设计。

 1 // strctfun.cpp -- functions with a structure argument
 2 #include <iostream>
 3 #include <cmath>
 4 
 5 // structure declarations
 6 struct polar
 7 {
 8     double distance;      // distance from origin
 9     double angle;         // direction from origin
10 };
11 struct rect
12 {
13     double x;             // horizontal distance from origin
14     double y;             // vertical distance from origin
15 };
16 
17 // prototypes
18 polar rect_to_polar(rect xypos);
19 void show_polar(polar dapos);
20 
21 int main()
22 {
23     using namespace std;
24     rect rplace;
25     polar pplace;
26 
27     cout << "Enter the x and y values: ";
28     while (cin >> rplace.x >> rplace.y)  // slick use of cin
29     {
30         pplace = rect_to_polar(rplace);
31         show_polar(pplace);
32         cout << "Next two numbers (q to quit): ";
33     }
34     cout << "Done.\n";
35     return 0;
36 }
37 
38 // convert rectangular to polar coordinates
39 polar rect_to_polar(rect xypos)
40 {
41     using namespace std;
42     polar answer;
43 
44     answer.distance =
45         sqrt( xypos.x * xypos.x + xypos.y * xypos.y);
46     answer.angle = atan2(xypos.y, xypos.x);
47     return answer;      // returns a polar structure
48 }
49 
50 // show polar coordinates, converting angle to degrees
51 void show_polar (polar dapos)
52 {
53     using namespace std;
54     const double Rad_to_deg = 57.29577951;
55 
56     cout << "distance = " << dapos.distance;
57     cout << ", angle = " << dapos.angle * Rad_to_deg;
58     cout << " degrees\n";
59 }
View Code

相关文章:

  • 2021-11-15
  • 2023-03-30
  • 2021-11-01
  • 2021-07-13
猜你喜欢
  • 2022-12-23
  • 2021-12-05
  • 2021-10-03
  • 2021-08-22
  • 2022-12-23
  • 2021-08-17
  • 2022-12-23
相关资源
相似解决方案