面向对象的编程风格

时间:2014-10-16 10:17:01

标签: c++ oop fstream

我正在用C ++学习OOP,但编程风格让我发疯。对于从文件输入的函数,哪种样式是OOP。谢谢!

class Point{
public:
   Point();
   ~Point();
   //<input from file>
private:
   int x, y;
}

风格1:

void Input(char* file_name){
   ifstream fin;
   fin.open(file_name);
   //<read the file>
   fin.close();
}

风格2:

void Input(ifstream &fin){
   //<read the file>
}

1 个答案:

答案 0 :(得分:3)

Point不应该特别关心文件。它可以为流操作符提供输入/输出到任何流类型。

class Point{
public:
    Point() : x(0), y(0) {}
    Point(int x, int y) : x(x), y(y) {}

   friend istream& operator >> (istream& is, Point& point)
   {
        return is >> point.x >> point.y;
   }

   friend ostream& operator << (ostream& os, const Point& point)
   {
        return os << point.x << " " << point.y << " ";
   }

private:
   int x, y;
}

ifstream file("file.txt");
Point p;
file >> p;