【002】初识C++ <二 > 保留关键字(Typedef)、构造器和析构器

来源:互联网 发布:实业难做 知乎 编辑:程序博客网 时间:2024/06/08 11:57

1.保留关键字  取别名(Typedef)

           


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 ;}







0 0
原创粉丝点击