看完Jerry Coffin对此的回答 question我将他的代码复制粘贴到我的编辑器中,经过一些小的编辑后,它可以正常编译和运行。
修改后的代码如下:
#include <iostream>
#include <string>
#include <istream>
#include <fstream>
class non_blank {
private:
std::string data_;
friend std::istream& operator>> (std::istream &is, non_blank &n) {
std::getline(is, n.data_);
if (n.data_.length() == 0) {
is.setstate(std::ios::failbit);
}
return is;
}
public:
operator std::string() const {
return data_;
}
};
int main(int, char *[]) {
non_blank line;
std::ifstream ifs("teste.txt");
while(ifs >> line) {
//std::cout << line; <----- error
std::string s = line;
std::cout << s << std::endl;
}
return 0;
}
尝试在
std::cout <<...
中使用非空变量时出现错误表达。我不应该在任何我会使用 std::string 的地方使用 non_blank 类型的变量吗?这不是强制转换/转换运算符的目的吗? answer为什么我不能访问私有(private)变量
string::data_
直接在operator >>
的定义中?
这是我得到的错误:
..\main.cpp: In function `std::istream& operator>>(std::istream&, non_blank&)':
..\main.cpp:21: error: invalid use of non-static data member `non_blank::data_'
..\main.cpp:26: error: from this location
最佳答案
Shouldn't I be able to use a variable of the type non_blank anywhere I would use a std::string? Isn't it the porpuse of the cast operator?
不完全是。如果编译器发现你在做它知道需要 std::string 的事情,它可以调用你的转换运算符来获得一个。但是在 ostream 运算符 << 的情况下,它没有要调用的单个特定函数,而是相当多的函数,它们各不相同,而且没有一个与您要打印的实际类型完全匹配。所以它列出了一大堆候选人,没有一个是足够强大的匹配。您需要为您的类型定义一个 ostream 运算符 << 以使其按应有的方式打印。
至于你的运算符(operator)>>,你应该让它不是你类(class)的成员。如果必须的话,在类声明中将其声明为友元,但将函数本身写在外面。
关于c++ - 读取文件直到空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4418773/