Menu
CoddyTech

불변 조건 보호

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

Java의 접근 제어자와 캡슐화 개념은 그대로 적용되지만, C++의 프렌드와 값 의미론은 인터페이스 설계에 영향을 줍니다. C++의 private 멤버는 접근을 제어합니다. private 상태를 수정할 수 있는 참조를 노출하는 대신 불변 조건을 유지하는 연산을 노출하세요.

Java

import java.util.*;
public class Example {
  static class Box { private int n; Box(int n) { this.n=n; } int getDouble() { return n*2; } }
  public static void main(String[] args) {
    System.out.println(new Box(3).getDouble());
  }
}

C++

#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
class Name {std::string text_;public:bool set(const std::string& s){if(s.empty())return false;text_=s;return true;}std::string get()const{return text_;}};
int main(){
Name n;std::cout<<std::boolalpha<<n.set("")<<" "<<n.set("oak")<<" "<<n.get()<<"\n";
}

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

challenge icon

챌린지

쉬움

입력: 초기 음이 아닌 용량에 이어 요청된 인출량이 주어집니다. Stock.take는 음이 아닌 양만큼 인출할 때, 잔량이 충분하면 성공을 반환하고, 그렇지 않으면 상태를 변경하지 않습니다. 성공 여부를 true/false로 출력한 다음 잔량을 출력하세요.

편집 가능한 모듈: Stock.cpp, Stock.hpp. 각 필수 형식에는 고유한 이름의 헤더와 구현 파일이 있습니다. 모든 공개 시그니처를 그대로 유지하세요. 잠금 상태인 main.cpp는 stdin을 읽고 API를 직접 호출합니다. 명시된 경우 공개 API의 동작도 별도로 확인합니다. API 내부에서 출력하지 말고 반환값을 사용하세요. 정수 입력과 결과는 부호 있는 int 범위에 들어갑니다. 달리 명시되지 않는 한 텍스트는 ASCII입니다.

직접 해보기

#include "Stock.hpp"
#include <iostream>
int main(){
{Stock s(5);if(!s.take(2)||s.take(4)||s.take(-1)||s.remaining()!=3||!s.take(3)||s.remaining()!=0)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,k;in>>n>>k;Stock s(n);bool ok=s.take(k);std::cout<<std::boolalpha<<ok<<" "<<s.remaining()<<"\n";
}
quiz icon실력 점검

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

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

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