[ Effective C++ ] 정리 모음집
" C++ 프로그래머의 필독서, 스콧 마이어스의 Effective C++ 를 읽고 내용 요약 / 정리 "
" 가상 함수는 동적 바인딩! 기본 매개변수는 정적 바인딩! "
- 위와 같은 이유로 상속받은 기본 매개변수 값은 절대 재정의 해서는 안 된다.
class Shape
{
public:
enum ShapeColor { Red, Green, Blue };
virtual void draw(ShapeColor color = Red) const = 0;
...
};
class Rectangle : public Shape
{
public:
virtual void draw(ShapeColor color = Green) const;
...
};
class Circle : public Shape
{
public
virtual void draw(ShapeColor color) const;
...
}
Shape* ps; // 정적 타입 = Shape*
Shape* pc = new Circle; // 정적 타입 = Shape*
Shape* pr = new Rectangle; // 정적 타입 = Shape*
Shape* ps; // 정적 타입 = Shape* // 동적 타입은 없음
Shape* pc = new Circle; // 정적 타입 = Shape* // 동적 타입 Circle*
Shape* pr = new Rectangle; // 정적 타입 = Shape* // 동적 타입 Rectangle*
ps = pc; // ps의 동적 타입은 이제 Circle*
ps = pr; // ps의 동적 타입은 이제 Circle*
pc->draw(Shape::Red); // Circle::draw(Shape::Red)
pr->draw(Shape::Red); // Rectangle::draw(Shape::Red)
pr->draw(); // Rectangle::draw(Shape::Red) 호출!
- Rectangle::draw
의 기본 매개변수는 Shape::Green
이지만, pr의 정적 타입이 Shape*
이므로 기본 매개변수도 Shape::draw()
의 기본 매개변수를 따라 Shape::Red
로 넘겨진다!
class Shape
{
public:
enum ShapeColor { Red, Green, Blue };
virtual void draw(ShapeColor color = Red) const = 0;
...
};
class Rectangle : public Shape
{
public
virtual void draw(ShapeColor color = Red) const;
...
};
Shape::draw
함수의 기본 매개변수 값이 바뀌면 파생 클래스 모두를 바꿔야 한다📢 비가상 인터페이스 관용구를 사용해 해결!
class Shape
{
public:
enum ShapeColor { Red, Green, Blue };
void draw(ShapeColor color = Red) const
{
doDraw(color);
}
...
private:
virtual void doDraw(ShapeColor color) const = 0;
};
class Rectangle : public Shape
{
public:
...
private:
virtual void doDraw(ShapeColor color) const;
...
};