对象2 构造,析构


#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()
{
    getline(std::cin, quote);
}

void StoreQuote::inputSpeaker()
{
    getline(std::cin, speaker);
}

bool StoreQuote::write()
{
    if(fileOutput.is_open())
    {
        fileOutput << quote << "!" << speaker << std::endl;
        return true;
    }
    else
    {
        return false;
    }
}


int main()
{
    StoreQuote sq;

    sq.inputQuote();
    sq.inputSpeaker();

    if(sq.write())
    {
        std::cout << "write ok" << std::endl;
    }
    else
    {
        std::cout << "write err" << std::endl;
    }
}
/* vim: set ts=4 sw=4 sts=4 tw=100 */
原文地址:https://www.cnblogs.com/i80386/p/4356553.html