메서드 (멤버 함수)
Coddy C++ 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨 — 104개 중 8번째.
멤버 함수는 객체가 무엇을 할 수 있는지를 정의합니다. 멤버 함수는 반환 타입, 이름, 그리고 선택적 매개변수를 가집니다.
값을 반환하는 메서드
class Calculator {
public:
int add(int a, int b) {
return a + b;
}
};Void 메서드 (반환값 없음)
class Printer {
public:
void printMessage(std::string msg) {
std::cout << msg << std::endl;
}
};bool을 반환하는 메서드
class Checker {
public:
bool isPositive(int num) {
return num > 0;
}
};헤더에서 선언하고 소스 파일에서 구현하기
// Calculator.h
class Calculator {
public:
int add(int a, int b);
};
// Calculator.cpp
int Calculator::add(int a, int b) {
return a + b;
}반환 타입은 메서드 이름 앞에 옵니다. 메서드가 아무것도 반환하지 않을 때는 void를 사용하세요. :: 범위 지정 연산자는 구현을 해당 클래스에 연결합니다.
챌린지
중급StringHelper 클래스에 대해 서로 다른 반환 타입과 매개변수를 가진 네 개의 멤버 함수를 구현하세요:
getLength()—int를 반환하며, 텍스트의 길이를 나타냅니다.toUpperCase()—std::string을 반환하며, 대문자로 변환된 텍스트입니다.contains(std::string word)—bool을 반환하며, 텍스트에 해당 단어가 포함되어 있는지 여부를 나타냅니다.repeat(int times)—std::string을 반환하며, 공백과 함께 반복된 텍스트입니다.
치트 시트
멤버 함수는 객체가 무엇을 할 수 있는지를 정의합니다. 멤버 함수는 반환 타입, 이름, 그리고 선택적인 매개변수를 가집니다.
값을 반환하는 메서드:
class Calculator {
public:
int add(int a, int b) {
return a + b;
}
};Void 메서드 (반환 값이 없음):
class Printer {
public:
void printMessage(std::string msg) {
std::cout << msg << std::endl;
}
};bool을 반환하는 메서드:
class Checker {
public:
bool isPositive(int num) {
return num > 0;
}
};헤더에서 선언하고 소스에서 구현하기:
// Calculator.h
class Calculator {
public:
int add(int a, int b);
};
// Calculator.cpp
int Calculator::add(int a, int b) {
return a + b;
}반환 타입은 메서드 이름 앞에 옵니다. 메서드가 아무것도 반환하지 않을 때는 void를 사용합니다. :: 범위 지정 연산자는 구현부를 해당 클래스에 연결합니다.
직접 해보기
#include <iostream>
#include "StringHelper.h"
int main() {
std::string input;
std::getline(std::cin, input);
StringHelper helper;
helper.text = input;
std::cout << "Original: " << helper.text << std::endl;
std::cout << "Length: " << helper.getLength() << std::endl;
std::cout << "Uppercase: " << helper.toUpperCase() << std::endl;
std::cout << "Contains 'World': " << (helper.contains("World") ? "yes" : "no") << std::endl;
std::cout << "Repeated: " << helper.repeat(3) << std::endl;
return 0;
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.