【发布时间】:2018-02-05 07:37:24
【问题描述】:
我在 C++ 中使用 fstream,它通过 main() 函数工作得很好。当我尝试使用头文件和相同的简单程序时,它不起作用。我想我需要在头文件中使用引用变量参数,但我只是不确定如何编写代码。可以这样写,让main函数去头文件取数据吗?
主要功能
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
#include "Prog_5_15.h"
using namespace std;
int main()
{
cout << "Hi Reed";
//I would like to try to keep the data in
//the Header File
//This works right
ofstream outputFile;
outputFile.open("e:\demofile2.txt");
cout << "Now writing data to the file\n";
outputFile << "Bach\n";
outputFile << "Beethoven\n";
outputFile << "Mozart\n";
outputFile << "Schubert\n";
outputFile.close();
// Can I put a function here from the Header File
// that gets info from fstream?
// Write_This(); ??
cin.get();
return 0;
}
头文件
#pragma once
#ifndef P515_h
#define P515_h
class Prog_5_15
{
public:
Prog_5_15();
ofstream outputFile2;
outputFile2.open("e:\demoFile3.txt");
outputFile2.close();
void Write_This(); // This part needs do be re-written
~Prog_5_15();
};
#endif // !P515_h
#include <iostream>
#include "Prog_5_15.h"
using namespace std;
Prog_5_15::Prog_5_15()
{
}
void Prog_5_15::Write_This() // This needs to be re-written I think
{
cout << "Now writing data to the file\n";
outputFile << "Bach\n";
outputFile << "Beethoven\n";
outputFile << "Mozart\n";
outputFile << "Schubert\n";
}
Prog_5_15::~Prog_5_15()
{
}
【问题讨论】:
-
获取一本 C++ 书籍并阅读有关类/对象的知识。
-
确实有很多需要重写的地方,但是你错了。
-
使用一种包含保护,而不是同时使用 #define 保护和 #pragma 一次
标签: c++ file reference header fstream