Menu
CoddyTech

메서드와 const 접근

Coddy의 Kotlin 개발자를 위한 C++ 코스 레슨. 48개 중 34번째.

Kotlin에는 const 멤버 함수가 없습니다. val은 참조에 다른 값을 다시 할당하는 것만 막습니다. 참조가 가리키는 객체는 여전히 어떤 메서드를 통해서든 변경할 수 있으며, MutableList 대신 List와 같이 더 제한적인 타입을 선택해야 읽기 전용으로 접근할 수 있습니다. C++ 인스턴스 메서드는 this를 암묵적으로 받습니다. const 멤버 함수는 해당 객체를 수정하지 않겠다고 보장하며, const 참조를 통해서는 const 멤버 함수만 호출할 수 있습니다.

Kotlin

class Badge(private var name: String) {
    fun rename(n: String) {
        name = n
    }

    fun label() = name
}

fun main() {
    val b = Badge("old")
    b.rename("new")
    println(b.label())
}

C++

#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
struct Badge {std::string name;void rename(std::string n){name=std::move(n);}std::string label()const{return name;}};
int main(){
Badge b{"old"};b.rename("new");const Badge& r=b;std::cout<<r.label()<<"\n";
}

각 프로그램을 독립적으로 추적해 보세요. 이 예제들은 과제와 다른 연산이나 데이터를 사용해 개념을 보여 줍니다. 소스 코드와 대상 코드의 출력이 같다고 가정하지 마세요.

challenge icon

챌린지

쉬움

입력: 시작 값과 부호가 있는 두 번의 변경 값입니다. Counter.add는 인스턴스를 변경하고, value는 const이며 현재 상태를 반환합니다.

편집 가능한 모듈: Counter.cpp, Counter.hpp. 각 필수 형식에는 자체 이름이 지정된 헤더와 구현 파일이 있습니다. 모든 공개 시그니처를 그대로 유지하세요. 잠긴 main.cpp는 표준 입력을 읽고 API를 직접 호출합니다. 또한 명시된 경우 공개 API 동작을 독립적으로 확인합니다. API 내부에서 출력하지 말고 값을 반환하세요. 정수 입력과 결과는 부호 있는 int 범위에 들어가며, 별도 언급이 없으면 텍스트는 ASCII입니다.

직접 해보기

#include "Counter.hpp"
#include <iostream>
int main(){
{Counter a(2),b(9);a.add(5);const Counter& r=a;if(r.value()!=7||b.value()!=9)return 21;}
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);int n,a,b;in>>n>>a>>b;Counter c(n);c.add(a);c.add(b);std::cout<<c.value()<<"\n";
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

Kotlin 개발자를 위한 C++의 모든 레슨

직접 연습해 보세요: 온라인 C++ 컴파일러