불변 조건 보호
Coddy의 Go 개발자를 위한 C++ 코스 레슨. 48개 중 36번째.
Go의 가시성은 패키지 범위와 내보낸 이름을 따릅니다. C++의 private 접근은 클래스 선언으로 제어됩니다. C++의 private 멤버는 접근 제어를 적용합니다. private 상태에 대한 쓰기 가능한 참조를 제공하는 대신 불변성을 유지하는 연산을 노출하세요.
Go
package main
import (
"fmt"
)
type Wallet struct { balance int }; func (w Wallet) Cents() int { return w.balance }
func main() {
w:=Wallet{balance:250}; fmt.Println(w.Cents())
}
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 안에서 출력하지 말고 반환값을 사용하세요. 정수 입력과 결과는 부호 있는 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";
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Go 개발자를 위한 C++의 모든 레슨
직접 연습해 보세요: 온라인 C++ 컴파일러