timruning 2016-02-22 15:02 采纳率: 50%
浏览 1295
已采纳

getline能否接受自动类型转换?

这个代码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();
}

  • 写回答

1条回答

  • 关注

    operator ifstream&() {
    return this->file;
    }
    指的是将FName1 类转换为ifstream&类型, 因为file是本类中ifstream的一个对象;return 语句return this->file;刚好将其转换过来。
    while (getline(file, s)) {
    cout << s << endl;
    }
    大家百度会发现getline()的原型是istream& getline ( istream &is , string &str , char delim );其中 istream &is 表示一个输入流,
    譬如cin;string&str表示把从输入流读入的字符串存放在这个字符串中(可以自己随便命名,str什么的都可以);char delim表示
    遇到这个字符停止读入,在不设置的情况下系统默认该字符为'\n',也就是回车换行符(遇到回车停止读入)。由于file是FName1类型的
    所以在getline(file, s)执行的时候,编译器隐式的将file转换成了ifstream&类型(通过调用operator ifstream&() ),这样不就参数匹配了嘛。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用