2014-10-16 4 views
-3

나는 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> 
} 
+0

모두가 아닙니다 .. void이어야합니다. Point :: Input (char * file_name); – lakesh

+1

@lakesh하지만 포인트 클래스는 입력 파일을 신경 쓰지 않아야합니다. – juanchopanza

+0

@lakesh 어떤 코딩 스타일이 라인에서 대체 될 수 있다는 것을 의미합니다. 스타일 1은 OOP를위한 것이라고 했지? –

답변

3

점은 특히 파일에 대해 신경 안된다. 스트림 연산자를 제공하여 모든 스트림 유형으로 입/출력 할 수 있습니다.

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; 
+0

@juanchopanza 감사합니다. –