E D R , A S I H C RSS

Constructor Parameter Method

Constructor Parameter Method

Constructor Method로 인스턴스를 만들때, 그리로 넘겨준 파라메터들을 새롭게 만들어진 인스턴스로 어떻게 갖고 오는가? 가장 유연한 방법은 각각의 변수에 대해 setter들을 만들어 주는 것이다. 즉,
~cpp 
class Point
{
/* ... */
	void setX(int x) { /* ... */ }
	void setY(int y) { /* ... */ }
	static Point* makeFromXnY(int x, int y)
	{
		Point* pt = new Point;
		pt->setX(x);
		pt->setY(y);
		return pt;
	}
/* ... */
};
이렇게 되는것이다. 하지만 변수가 많아질수록 setter들은 계속 늘어난다. 이럴때에는 모든 변수를 한번에 set해주는 하나의 메소드를 만든다. 그리고 접두사를 set으로 명명해주고 변수의 이름을 딸려준다.
~cpp 
class Point
{
/* ... */
	static Point* makeFromXnY(int x, int y)
	{
		Point* pt = new Point;
		pt->setXnY(x,y);
		return pt;
	}
	void setXnY(int x, int y) // smalltalk에서는 setX:xNum y:yNum이라는 메세지를 사용한다.
	{
		this->x = x;
		this->y = y;
	}
/* ... */
};

Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2021-02-07 05:23:00
Processing time 0.0076 sec