값에 의한 컴포지션
Coddy의 C# 개발자를 위한 C++ 코스 레슨. 48개 중 38번째.
C# 클래스 필드는 일반적으로 참조를 보유하지만, C++ 멤버는 포함된 객체를 직접 소유하고 자동 수명을 가질 수 있습니다. C++ 값 멤버는 소유자와 함께 생성되고 소멸됩니다. has-a 관계에 동적 할당이 꼭 필요한 것은 아닙니다.
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
class Badge {public string Name;public Badge(string n){Name=n;}} class Envelope {public Badge Badge;public Envelope(Badge b){Badge=b;}}
static void Main() {
var e=new Envelope(new Badge("Ada"));Console.WriteLine(e.Badge.Name);
}
}
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;};struct Envelope{Badge badge;};
int main(){
Envelope e{{"Ada"}};std::cout<<e.badge.name<<"\n";
}
각 프로그램을 독립적으로 추적하세요. 이 예제들은 과제와 다른 연산이나 데이터를 사용해 개념을 보여 줍니다. 원본 출력과 대상 출력이 일치한다고 가정하지 마세요.
챌린지
쉬움입력: 음수가 아닌 단가, 수량, 고정 배송비. Order는 Item을 값으로 소유합니다. Item.subtotal은 가격에 수량을 곱한 값이고, Order.total은 소유한 Item의 소계에 배송비를 더합니다.
편집 가능한 모듈: Item.cpp, Item.hpp, Order.cpp, Order.hpp. 각 필수 타입에는 이름이 지정된 헤더와 구현 파일이 있습니다. 모든 공개 시그니처를 그대로 유지하세요. 잠긴 main.cpp는 stdin을 읽고 API를 직접 호출합니다. 또한 명시된 경우 공개 API의 동작을 독립적으로 확인합니다. API 내부에서 출력하지 말고 값을 반환하세요. 정수 입력과 결과는 부호 있는 int 범위에 들어가며, 별도 언급이 없으면 텍스트는 ASCII입니다.
직접 해보기
#include "Item.hpp"
#include "Order.hpp"
#include <iostream>
int main(){
{Item i(7,2);Order a(i,3),b(Item(2,4),1);if(i.subtotal()!=14||a.total()!=17||b.total()!=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 p,q,s;in>>p>>q>>s;Item i(p,q);Order o(i,s);std::cout<<o.total()<<"\n";
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C# 개발자를 위한 C++의 모든 레슨
직접 연습해 보세요: 온라인 C++ 컴파일러