ABOUT ME

Today
Yesterday
Total
  • 정적 멤버 (1)
    C++ 2021. 12. 23. 13:00

    https://www.youtube.com/watch?v=SJx5czHKSy8&list=PLlJhQXcLQBJqywc5dweQ75GBRubzPxhAk&index=63

     

    1. static

    #include <iostream>
    
    using namespace std;
    
    class Color {
    public:
    	Color() : r(0), g(0), b(0) { }
    	Color(float r, float g, float b) : r(r), g(g), b(b) { }
    	
    	float GetR() { return r; }
    	float GetG() { return g; }
    	float GetB() { return b; }
    private:
    	float r;
    	float g;
    	float b;
    };
    
    Color MixColors(Color a, Color b) {
    	return Color((a.GetR() + b.GetR()) / 2, (a.GetG() + b.GetG()) / 2, (a.GetB() + b.GetB()) / 2);
    }
    
    int main() {
    	Color blue(0, 0, 1);
    	Color red(1, 0, 0);
    
    	Color mix = MixColors(blue, red);
    
    	cout << "mixR : " << mix.GetR() << endl << "mixG : " << mix.GetG() << endl << "mixB : " << mix.GetB() << endl;
    }

    위의 코드를 보면 Color클래스와 MixColors 함수는 밀접한 관련이 있기 때문에 Color클래스에 모두 담아두고 싶어진다.

    그러나 MixColors 함수를 Color클래스 안에 넣어두면 호출할 때 애매한 상황이 벌어지는데 이것을 static을 통해 해결할 수 있다.

     

    #include <iostream>
    
    using namespace std;
    
    class Color {
    public:
    	Color() : r(0), g(0), b(0) { }
    	Color(float r, float g, float b) : r(r), g(g), b(b) { }
    	
    	float GetR() { return r; }
    	float GetG() { return g; }
    	float GetB() { return b; }
    
    	static Color MixColors(Color a, Color b) {
    		return Color((a.GetR() + b.GetR()) / 2, (a.GetG() + b.GetG()) / 2, (a.GetB() + b.GetB()) / 2);
    	}
    
    private:
    	float r;
    	float g;
    	float b;
    };
    
    int main() {
    	Color blue(0, 0, 1);
    	Color red(1, 0, 0);
    
    	Color mix = Color::MixColors(blue, red);
    
    	cout << "mixR : " << mix.GetR() << endl << "mixG : " << mix.GetG() << endl << "mixB : " << mix.GetB() << endl;
    }

    static을 사용한 함수는 "클래스명::함수명( );" 과 같이 호출할 수 있다.

    그리고 Color클래스에 포함되어 있기 때문에 private으로 선언된 r, g, b값들에 직접적으로 접근할 수 있게 된다.

    blue.MixColors(blue, red);와 같이 접근할 수도 있지만 잘 사용하지는 않는다.

    'C++' 카테고리의 다른 글

    상수형 매개변수와 상수형 메서드  (0) 2021.12.23
    정적 멤버 (2)  (0) 2021.12.23
    생성자의 다양한 사용 방법  (0) 2021.12.23
    객체의 생성과 소멸  (0) 2021.12.21
    this 포인터  (0) 2021.12.21
Designed by Tistory.