混迹C++ 之构造器和析构器

构造器和析构器的使用

#include <iostream>
#include <string>
#include <fstream>//file-stream

class StoreQuote
{
public:
  std::string quote,speaker;
  std::ofstream fileOutput;
  /*文件输出函数,建立一个文件,如果没有,则创建它*/
 
  StoreQuote();//定义构造器
  ~StoreQuote();//定义析构器
  void inputQuote();//写入名言
  void inputSpeaker();//写入作者
  bool write();
protected:

};

StoreQuote::StoreQuote()
{
  fileOutput.open("测试.txt",std::ios::app);//初始化工作,申请内存等。
  /*以追加(append)的形式打开*/
}
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<<"成功写入文件"<<std::endl;
    }
  else
    {
      std::cout<<"写入文件失败"<<std::endl;//同样这里写endl的时候,需指明它的作用域
      return 1;
    }
  return 0;
}
//参考:www.fishc.com


你可能感兴趣的:(混迹C++ 之构造器和析构器)