构造器的名字必须和它所在的类的名字一样;
析构器就是构造器前面加‘~’
构造器永远不会返回任何值
系统在创建某个类的实例时会第一时间自动调用这个类的构造器
故在下列代码中可以省去在main函数里写文件写入的相关代码
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class Storestory
{
public:
string story,writer;
Storestory();//构造器
~Storestory();//析构器
ofstream writefile;//写入文件定义
void writestory();//写故事
void writewriter(); //写作者
bool write();//判断文件是否打开
};
Storestory::Storestory()
{
writefile.open("E:\\user.txt",ios::app);
//构造器里用追加形式打开文件
}
Storestory::~Storestory()
{
writefile.close();
//析构器关闭文件
}
void Storestory::writestory()
{
cin.ignore(100,'\n');//吃掉回车避免麻烦
getline(cin,story);
cout<<"故事:"<<story<<endl;
}
void Storestory::writewriter()
{
cin.ignore(100,'\n');
getline(cin,writer);
cout<<"作者:"<<writer<<endl;
}
bool Storestory::write()
{
if(writefile.is_open()) return true;
else return false;
}
int main()
{
Storestory ss;
cout<<"我有故事,你有酒吗?"<<endl;
ss.writestory();
cout<<"这个故事是谁的呢?"<<endl;
ss.writewriter();
if(ss.write()) cout<<"这个故事将被记录于此"<<endl;
else cout<<"文件打开失败,故事记录失败"<<endl;
return 0;
}