【002】初识C++ <二 > 保留关键字(Typedef)、构造器和析构器
2015-01-27 11:35
357 查看
1.保留关键字 取别名(Typedef)
2.对象的创建
属性+方法!
3.1定义构造器
3.2 定义析构器
代码练习:
2.对象的创建
属性+方法!
3.1定义构造器
对于你自己写的类,如果你没有自己写构造函数,编译器会自动给你产生一个构造函数,让你调用。
3.2 定义析构器
析构器,也就是析构函数,当一个对象在消亡的时候,由编译器自动调用。对于系统自带的类型,例如int,char等,它的析构函数是由编译器提供的,对于你自己定义的类,它的析构函数是你自己写的。 对象在什么时候消亡呢? 对于普通的对象来说,就是在离开它的作用域的时候,比如你在一个函数里定义了一个对象,在跳出函数的时候,它就消亡了。
顺带说下new delete malloc free的区别,
int *p = new int();这个时候调用构造函数
delete p;这个时候调用析构函数
int *p = (int *)malloc(sizeof(int));这个时候不会调用构造函数
free(p);这个时候不会调用析构函数。
另外假如你定义一个类
class person{
public:
person();
persion(int age);
};
person myperson;这个时候会调用person();
person yourperson(10);这个时候会调用persion(int age);
代码练习:
#include <iostream> #include <string> #include<fstream> class StoreQuote { public: std::string quote,speaker; std::ofstream fileOutput; StoreQuote(); ~StoreQuote(); void inputQuote(); void inputSpeaker(); bool write(); }; StoreQuote::StoreQuote(){ fileOutput.open("test.txt",std::ios::app); } StoreQuote::~StoreQuote(){ fileOutput.close(); } void StoreQuote::inputQuote(){ std::getline(std::cin,quote); } void StoreQuote::inputSpeaker(){ std::getline(std::cin,speaker); } bool StoreQuote::write(){ if( fileOutput.is_open()) { fileOutput<<quote<<"|"<<speaker<<"\n"; return true; }else{ return false; } } int main(){ StoreQuote quote; std::cout<<"请输入一句名言:\n"; quote.inputQuote(); std::cout<<"请输入作者:\n"; quote.inputSpeaker(); if( quote.write() ){ std::cout<<"写入文件成功!\n"; } else{ std::cout<<" 写入文件失败!\n"; return 1; } return 0 ; }
相关文章推荐
- Java笔记2 面向对象<2>static关键字、main函数、静态运用、单例设计模式
- K&R的名著:<C程序设计语言>小程序总结p117统计关键字
- spring data jpa中@Query中的模糊查询<like关键字>
- <fmt:formatNumber> 最多保留小数部分几位
- C++类型转换关键字 *_cast<type> (expression)
- <C/C++基础>关键字typedef用法总结
- 在HTML中输出文本需要保留空格和换行符时需要加 <pre>
- <菜鸟必看>初识for增强循环
- 黑 马 程 序 员_视频学习总结<C语言>----07 static和extern关键字、typedef
- 关于C++const关键字的一些总结<一>
- 一起学Maven(初识Maven)<一>
- final 关键字 和 static 用法<转>
- 一起学Maven(Maven仓库管理器之初识Nexus)<五>
- Java笔记2 面向对象<3>final关键字、抽象类、模板方法模式、接口
- HTML 简单教程-实例002 HTML标题<h1> - <h6> 标签
- ASP.NET web.config里 <connectionStrings>关键字简介
- typedef std::vector<Byte> ByteVector
- <Android>初识一:令人头疼的R文件缺失问题
- JavaSE笔记之<final关键字>
- C语言复习笔记<1>——关键字的用法