第六周 课后实践--阅读程序
来源:互联网 发布:2017香港mac口红多少钱 编辑:程序博客网 时间:2024/05/19 13:16
代码:
/**Copyright (c) 2015,烟台大学计算机学院*All rights reserved.*文件名称:test.cpp*作者:吴胜男*完成日期:2015年04月12日*版本号:v1.0**问题描述:阅读程序!!*输入描述:*程序输出:*/#include <iostream>using namespace std;class A{public: A() { cout<<"A"; } ~A() { cout<<"~A"; }};class B{ A *p;public: B() { cout<<"B"; p=new A(); } ~B() { cout<<"~B"; delete p; }};int main(){ B obj; return 0;}
运行结果:
总结:对A对象的析构函数只有在new释放空间的时候才进行调用。
代码:
#include <iostream>using namespace std;class MyClass{public: MyClass(int x=0):i(x) { cout<<"C"<<i; } ~MyClass() { cout<<"D"<<i; } void SetValue(int val) { i=val; } int GetVal() { return i; }private: int i;};int main(){ MyClass *p[3]; int i; for (i=0; i<3; i++) { p[i]=new MyClass(i); p[i]->SetValue(p[i]->GetVal()*2); } for (i=0; i<3; i++) delete p[i]; cout<<endl; return 0;}
运行结果:
总结:先释放哪个数组执行哪个析构函数。
代码:
#include <iostream>using namespace std;class B{public: B() { cout<<"default constructor"<<endl; } ~B() { cout<<"destructed"<<endl; } B(int i):data(i) { cout<<"constructed: " << data <<endl; }private: int data;};B Play(B b){ return b ;}int main(){ B temp = Play(5); return 0;}
运行结果:
总结:B Play(B b) { return b ;} 声明一个对象play,参数为对象b, 在main函数中定义一个对象temp 将play(5)的值赋给temp,play(5)输出constructed: 5..对象b释放执行析构函数输出destructed 对象play执行完毕释放再执行析构函数,输出destructed。
代码:
#include <iostream>using namespace std;class example{public: example() { cout<<"Default Constructing! "<<endl; } example(int n) { i=n; cout<<"Constructing: "<<i<<endl; } ~example() { cout <<"Destructing: "<<i<<endl; } int get_i() { return i; }private: int i;};int sqr_it(example o){ return o.get_i()* o.get_i();}int main(){ example x(10); cout<<x.get_i()<<endl; cout<<sqr_it(x)<<endl; return 0;}
运行结果;
总结:建立一次对象执行一次析构函数。
代码:
#include <iostream>using namespace std;class AA{public: AA(int i,int j) { A=i; B=j; cout<<"Constructor\n"; } AA(AA &obj) { A=obj.A+1; B=obj.B+2; cout<<"Copy_Constructor\n"; } ~AA() { cout<<"Destructor\n"; } void print() { cout<<"A="<<A<<",B="<<B<<endl; }private: int A,B;};int main(){ AA a1(2,3); AA a2(a1); a2.print(); AA *pa=new AA(5,6); pa->print(); delete pa; return 0;}
运行结果:
总结:注意析构函数的调用次数。
0 0
- 第六周 课后实践--阅读程序
- 第六周课后实践:阅读程序
- 第六周 课后实践:阅读程序
- 第六周 课后实践:阅读程序
- 第二周课后实践-阅读程序
- 第二周课后实践--阅读程序
- 第二周课后实践阅读程序
- 第二周--课后实践:阅读程序
- 第二周 课后实践 程序阅读
- 第二周 课后实践 阅读程序2
- 第三周课后实践-阅读程序
- 第三周 课后实践 阅读程序
- 第三周课后实践 阅读程序
- 第三周 课后实践--阅读程序
- 第三周课后实践:阅读程序
- 第五周课后实践:阅读程序
- 第八周课后实践:阅读程序
- 第八周 课后实践:阅读程序
- LeetCode OJ Consecutive Numbers
- C # 根据字符串动态的创建对象 类 反射
- Json 和 Jsonlib 的使用
- 关于错误:textAppearanceLargePopupMenu requires API level 11 (current min is 8)
- 浅谈 js中parseInt函数的解析
- 第六周 课后实践--阅读程序
- leetcode 20 Valid Parentheses
- [Leetcode] 1. Two Sum
- 【Objective-C学习笔记】内存管理
- 关键字static、final使用小结
- js动态添加div
- 替换字符串中的字母
- IDA知其所以然
- Java开发工具Eclipse安装