불변식 보호
Coddy의 C 개발자를 위한 C++ 코스 레슨. 48개 중 36번째.
C 라이브러리는 종종 불투명 포인터 뒤에 구조체 정의를 숨깁니다. C++의 비공개 필드는 형식 내부에서만 접근하도록 제한하고, 공개 메서드는 불변 조건을 보호합니다. 게터는 상태에 대해 선택한 관점을 노출합니다. 쓰기 가능한 참조를 반환하면 유효성 검사 정책을 실수로 우회할 수 있습니다.
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
struct Name {const char* text;};int set_name(struct Name* n,const char* s){if(!*s)return 0;n->text=s;return 1;}
int main(void){
struct Name n={""};int a=set_name(&n,"");int b=set_name(&n,"oak");printf("%s %s %s\n",a?"true":"false",b?"true":"false",n.text);
return 0;
}
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";
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C 개발자를 위한 C++의 모든 레슨
직접 연습해 보세요: 온라인 C++ 컴파일러