1)代码
#include <iostream>
#include <vector>
#include <fstream>
class Point {
public:
int x;
std::string b;
std::ofstream *of;
int y;
};
int main() {
std::vector<Point> points;
std::ofstream outfile;
outfile.open("tmp.txt");
Point pt1 = {1,"b1", &outfile, 2};
std::ofstream outfile2;
Point pt2 = {3,"b2", &outfile2, 4};
points.push_back(pt1);
points.push_back(pt2);
std::cout<< points[0].x << ", " << points[0].b << ", "<< points[0].y << std::endl;
std::cout<< points[1].x << ", " << points[1].b << ", "<< points[1].y << std::endl;
points[0].of << "hello world\n";
return 0;
}
2)报错
a2.vector.cpp: In function 'int main()':
a2.vector.cpp:22:18: error: invalid operands of types 'std::ofstream*' {aka 'std::basic_ofstream<char>*'} and 'const char [13]' to binary 'operator<<'
points[0].of << "hello world\n";
3)
错误分析
points[0].of是个引用,因为前面 std::ofstream *of;是定义是的一个指针,
所以要加*
4)
points[0].of << "hello world\n";
改成
points[0].*of << "hello world\n";
仍然报错
a2.vector.cpp: In function 'int main()':
a2.vector.cpp:22:16: error: 'of' was not declared in this scope
points[0].*of << "hello world\n";
^~
a2.vector.cpp:22:16: note: suggested alternative: 'feof'
points[0].*of << "hello world\n";
5)
points[0].of << "hello world\n";
改成
*points[0].of << "hello world\n";
其实应该是 *(points[0].of) << "hello world\n";
就对了。

被折叠的 条评论
为什么被折叠?



