불변 조건 보호
Coddy의 Swift 개발자를 위한 C++ 코스 레슨. 48개 중 36번째.
Swift의 접근 제어는 선언, 파일, 모듈을 기준으로 범위가 정해집니다. private는 멤버를 해당 멤버를 둘러싼 선언부와 같은 파일의 확장부 외부에서 숨기며, private(set)을 사용하면 호출자는 속성을 읽을 수 있지만 값을 할당할 수는 없습니다. C++의 private 멤버는 호출 코드가 어디에 있든 해당 클래스의 멤버 함수와 친구 함수에서만 접근할 수 있습니다. 어느 언어에서든 불변 조건을 의도적으로 설계한 공개 API 뒤에 두세요. private 상태를 직접 쓸 수 있는 참조를 공개하는 대신, 불변 조건을 보존하는 연산을 공개하세요.
Swift
struct Meter {
private(set) var level = 0
mutating func raise(by amount: Int) -> Bool {
guard amount > 0, level + amount <= 10 else { return false }
level += amount
return true
}
}
var m = Meter()
print(m.raise(by: 3), m.raise(by: 20), m.level)
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";
}
각 프로그램을 독립적으로 추적해 보세요. 이 예제들은 과제와 다른 연산이나 데이터를 사용해 개념을 보여 줍니다. 소스와 대상의 출력이 일치한다고 가정하지 마세요.
챌린지
쉬움입력: 초기 비음수 용량, 이어서 요청된 인출량. Stock.take는 남은 양이 충분한 경우에만 비음수 양을 받아들이고 성공을 반환하며, 그렇지 않으면 상태를 변경하지 않습니다. 성공 여부를 true/false로 출력한 다음 남은 양을 출력하세요.
편집 가능한 모듈: Stock.cpp, Stock.hpp. 각 필수 타입에는 고유한 이름의 헤더와 구현 파일이 있습니다. 모든 공개 시그니처를 보존하세요. 잠긴 main.cpp는 stdin을 읽고 API를 직접 호출합니다. 또한 명시된 경우 공개 API 동작을 독립적으로 확인합니다. API 내부에서 출력하지 말고 값을 반환하세요. 정수 입력과 결과는 signed 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";
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Swift 개발자를 위한 C++의 모든 레슨
직접 연습해 보세요: 온라인 C++ 컴파일러