这个代码getline接收参数有bug。
我不明白为啥FName1有类型转换函数,getline函数还是不能接受file对象呢,应该能够自动按照ifstream接收呀。
我试了print函数,里面有getline,接收的参数类型是ifstream&,是没有问题的。
本来以为编译器不接受函数参数多次类型转换,但自己试的代码也是没问题的(从一个类型利用operator转换到另一个类型,再转换为基类类型)
#include
#include
#include
using namespace std;
class FName1 {
ifstream file;
string fileName;
bool named;
public:
FName1() :named(false) {}
FName1(const string& fname)
:fileName(fname), file(fname.c_str()) {
named = true;
}
string name() const {
return fileName;
}
void name(const string& newName) {
if (named)
return;
fileName = newName;
named = true;
}
operator ifstream&() {
return this->file;
}
// ifstream& ifstreamobject(){
// return file;
// }
void close() {
file.close();
}
};
void print(ifstream& in) {
string s;
while (getline(in,s))
{
cout << s << endl;
}
return;
}
int main() {
FName1 file("out.dat");
cout << "file.name()" << endl;
string s;
while (getline(file, s)) {
cout << s << endl;
}
print(file);
file.close();
}