-
멤버 메서드 활용하기C++ 2021. 12. 23. 15:00
https://www.youtube.com/watch?v=QaCpk53KuNg&list=PLlJhQXcLQBJqywc5dweQ75GBRubzPxhAk&index=66
1. 멤버 메서드의 선언, 정의 분리하기
#include <iostream> using namespace std; class Vector2 { public: Vector2(); Vector2(float x, float y); float GetX() const; float GetY() const; private: float x; float y; }; int main() { Vector2 a(2, 3); Vector2 b(-1, 4); cout << "a : (" << a.GetX() << ", " << a.GetY() << ")" << endl; cout << "b : (" << b.GetX() << ", " << b.GetY() << ")" << endl; } Vector2::Vector2() : x(0), y(0) { } Vector2::Vector2(float x, float y) : x(x), y(y) { } float Vector2::GetX() const { return x; } float Vector2::GetY() const { return y; }
클래스의 생성자와 메소드는 네임스페이스처럼 선언과 정의를 분리할 수 있다.
2. 멤버 메서드 활용
두 벡터를 더하는 연산을 수행하는 메서드를 구현해보자.
#include <iostream> using namespace std; class Vector2 { public: Vector2(); Vector2(float x, float y); float GetX() const; float GetY() const; static Vector2 Sum(Vector2 a, Vector2 b) { return Vector2(a.x + b.x, a.y + b.y); } Vector2 Add(Vector2 rhs) { return Vector2(x + rhs.GetX(), y + rhs.GetY()); } private: float x; float y; }; int main() { Vector2 a(2, 3); Vector2 b(-1, 4); Vector2 c1 = Vector2::Sum(a, b); Vector2 c2 = a.Add(b); cout << "a : (" << a.GetX() << ", " << a.GetY() << ")" << endl; cout << "b : (" << b.GetX() << ", " << b.GetY() << ")" << endl; cout << "c1 : (" << c1.GetX() << ", " << c1.GetY() << ")" << endl; cout << "c2 : (" << c2.GetX() << ", " << c2.GetY() << ")" << endl; } Vector2::Vector2() : x(0), y(0) { } Vector2::Vector2(float x, float y) : x(x), y(y) { } float Vector2::GetX() const { return x; } float Vector2::GetY() const { return y; }
1.의 코드에서 Sum과 Add메서드를 추가했다.
Sum은 static을 사용하여 구현하였고 Add는 동적으로 선언하였다.
'C++' 카테고리의 다른 글
8부 (클래스) 종합문제 - 1 (0) 2021.12.23 연산자 오버로딩 (0) 2021.12.23 상수형 매개변수와 상수형 메서드 (0) 2021.12.23 정적 멤버 (2) (0) 2021.12.23 정적 멤버 (1) (0) 2021.12.23