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";
points[0].of.close();
return 0;
2)报错
a2.vector.cpp: In function 'int main()':
a2.vector.cpp:23:18: error: request for member 'close' in 'points.std::vector<Point>::operator[](0).Point::of', which is of pointer type 'std::ofstream*' {aka 'std::basic_ofstream<char>*'} (maybe you meant to use '->' ?)
points[0].of.close();
3)
(points[0].of).close();
改成
(points[0].of)->close();
4)输出结果
1, b1, 2
3, b2, 4
tmp.txt中也有数据
hello world
5)
最终代码是这样的
#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";
(points[0].of)->close();
return 0;
}