메서드 (멤버 함수)
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를 사용합니다. :: 범위 확인 연산자는 구현을 해당 class에 연결합니다.
챌린지
중급StringHelper 클래스에 서로 다른 반환 유형과 매개변수를 사용하는 네 개의 멤버 함수를 구현하세요:
getLength():int를 반환하며, 텍스트의 길이를 나타냅니다toUpperCase():std::string을 반환하며, 대문자로 변환된 텍스트를 나타냅니다contains(std::string word):bool을 반환하며, 텍스트에 해당 단어가 포함되어 있는지를 나타냅니다repeat(int times):std::string을 반환하며, 공백으로 구분해 반복된 텍스트를 나타냅니다
직접 해보기
#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;
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: 온라인 C++ 컴파일러