|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 Sì曾相識♂ 于 2013-7-13 22:17 编辑
刚在看小甲鱼C++视频的第十五讲:不是每滴牛奶都叫特仑苏(构造器和析构函数讲解)
先上代码,然后来说下我的不解:
- #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 << "成功写入文件^_^";
- }
- else
- {
- std::cout << "写入文件失败T_T";
- return 1;
- }
-
- return 0;
- }
复制代码 从以上的代码可以看出,小甲鱼虽然有给析构函数 添加实现代码,但是在main函数中并没有调用析构函数。
于是我的不解就来了,难道析构函数跟构造函数一样会自己自动调用?如果自己自动调用的话,那又是何时去调用呢?系统如何判断什么时候该调用呢???
本人C++菜鸟,还请各位大神指点一二。
另外在简单的问一句,现在C++视频的课后习题答案在哪里??论坛改版了,找不到了....:'(
PS:小甲鱼的最后附图不错(并不是每滴牛奶都叫特仑苏那张....):lol
|
|