实验5 类和对象-3(未完)

1.ex3.cpp完整程序及运行截图

 1 #include <iostream>
 2 #include <vector>
 3 #include <string>
 4 using namespace std;
 5 
 6 // 函数声明 
 7 void output1(vector<string> &);  
 8 void output2(vector<string> &);  
 9 
10 int main()
11 {
12     vector<string>likes, dislikes; // 创建vector<string>对象likes和dislikes
13     
14     // 为vector<string>数组对象likes添加元素值 ( favorite book, music, film, paintings,anime,sport,sportsman,etc) 
15     // 补足代码 
16     // 。。。
17     likes.push_back("favorite book");
18     likes.push_back("music");
19     likes.push_back("film");
20     likes.push_back("painting");
21     
22     cout << "-----I like these-----" << endl;
23     // 调用子函数输出vector<string>数组对象likes的元素值 
24     // 补足代码
25     // 。。。 
26     output1(likes);
27 
28     
29     // 为vector<string>数组对象dislikes添加元素值 
30     // 补足代码 
31     // 。。。 
32     dislikes.push_back("anime");
33     dislikes.push_back("sport");
34     dislikes.push_back("sportsman"); 
35     
36     cout << "-----I dislike these-----" << endl;
37     // 调用子函数输出vector<string>数组对象dislikes的元素值 
38     // 补足代码
39     // 。。。 
40     output2(dislikes);
41 
42     
43     // 交换vector<string>对象likes和dislikes的元素值 
44     // 补足代码
45     // 。。。 
46     likes.swap(dislikes);
47     
48     
49     cout << "-----I likes these-----" << endl;
50     // 调用子函数输出vector<string>数组对象likes的元素值 
51     // 补足代码
52     // 。。。 
53     output2(likes);
54 
55     cout << "-----I dislikes these-----" << endl;
56     // 调用子函数输出vector<string>数组对象dislikes的元素值 
57     // 补足代码
58     // 。。。 
59     output1(dislikes);
60         
61                         
62     return 0;
63 }
64 
65 
66 // 函数实现 
67 // 以下标方式输出vector<string>数组对象v的元素值  
68 void output1(vector<string> &v) {
69     // 补足程序
70     // 。。。 
71     for(int i=0;i<v.size();i++)
72     cout<<v[i]<<",";
73     cout<<endl;
74 }
75 
76 // 函数实现
77 // 以迭代器方式输出vector<string>数组对象v的元素值 
78 void output2(vector<string> &v) {
79     // 补足程序
80     // 。。。 
81     vector<string>::iterator it1=v.begin();
82     vector<string>::iterator it2=v.end();
83     for(;it1!=it2;it1++)
84     cout<<*it1<<",";
85     cout<<endl;
86 }

2.关于6-17程序的修改

 1 #include<iostream>
 2 using namespace std;
 3 int main()
 4 {
 5     int *p;
 6     p=new int(9);
 7     cout<<"The value at p:"<<*p;
 8     delete p;
 9     return 0;
10  } 

3.关于6-18程序的修改

 1 #include<iostream>
 2 using namespace std;
 3 int fn1(){
 4     int *p=new int(5);
 5     int reserve=*p;
 6     delete p;
 7     return reserve; 
 8 } 
 9 int main(){
10     int a=fn1();
11     cout<<"the value of a is:"<<a;
12     return 0;
13 }

这道题一开始没看出什么问题,参考了同学的博客修改的。

书p219   注意  “用new 分配的内存,必须用delete加以释放,否则会导致动态分配的内存无法回收,使得程序占据的内存越来越大,这叫做‘内存泄漏’。”

猜你喜欢

转载自www.cnblogs.com/ditongwoshang/p/9070563.html
今日推荐