생성자 초기화
Coddy의 Dart 개발자를 위한 C++ 코스 레슨. 48개 중 33번째.
Dart는 각 새 인스턴스에 대해 생성자 본문이 실행되기 전에 필드 초기화와 생성자의 초기화 목록(Bag(String name) : label = name.toUpperCase())을 실행하며, 이때까지 모든 final 필드가 설정되어 있어야 합니다. Dart는 초기화 목록 항목을 작성한 순서대로 평가합니다. C++ 생성자는 불변 조건을 설정합니다. 멤버 초기화 목록은 필드를 초기화하며, 실제 초기화는 멤버 선언 순서를 따릅니다.
Dart
class Bag {
final List<int> items = [];
final String label;
Bag(String name) : label = name.toUpperCase();
}
void main() {
final a = Bag('a'), b = Bag('b');
a.items.add(1);
print('${b.label} ${b.items.length}');
}
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;explicit Badge(std::string n):name(std::move(n)){} };
int main(){
Badge b("Ada");std::cout<<b.name<<"\n";
}
각 프로그램을 독립적으로 추적하세요. 이 예제들은 과제와 다른 연산이나 데이터를 사용해 개념을 보여 줍니다. 소스 출력과 대상 출력이 일치한다고 가정하지 마세요.
챌린지
쉬움입력: 정수 시작 잔액과 음수가 아닌 입금액입니다. Wallet은 max(start,0)으로 초기화되고, add는 잔액을 늘리며, balance는 현재 금액을 반환합니다.
편집 가능한 모듈: Wallet.cpp, Wallet.hpp. 필요한 각 형식은 자체 이름의 헤더와 구현 파일을 갖습니다. 모든 public 시그니처를 유지하세요. 잠긴 main.cpp는 stdin을 읽고 API를 직접 호출합니다. 또한 명시된 경우 public API 동작을 독립적으로 확인합니다. API 내부에서 출력하지 말고 값을 반환하세요. 정수 입력과 결과는 signed int 범위에 들어가며, 별도로 명시되지 않는 한 텍스트는 ASCII입니다.
직접 해보기
#include "Wallet.hpp"
#include <iostream>
int main(){
{Wallet a(-2),b(7);a.add(3);a.add(4);if(a.balance()!=7||b.balance()!=7)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,d;in>>n>>d;Wallet w(n);w.add(d);std::cout<<w.balance()<<"\n";
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Dart 개발자를 위한 C++의 모든 레슨
직접 연습해 보세요: 온라인 C++ 컴파일러