Menu
CoddyTech

상속과 재정의

Coddy의 C++ 개발자를 위한 Swift 코스 레슨. 48개 중 37번째.

C++은 베이스 포인터나 참조를 통한 동적 디스패치를 위해 virtual 베이스 멤버가 필요하며, override는 파생 선언이 실제로 이를 오버라이드하는지 검사합니다. Swift 클래스 메서드는 final이 아닌 이상 허용된 범위 내에서 일반적으로 오버라이드할 수 있으며, 서브클래스에서는 override를 작성합니다. 모듈 간 Swift 서브클래싱에는 open 접근 제어도 포함됩니다. C++은 다중 클래스 상속을 허용하는 반면, Swift는 단일 클래스 슈퍼클래스만 허용하며 추가 기능을 위해 프로토콜을 사용합니다. 동적 동작을 보존하는 것이 중요할 때는 C++ 파생 값을 베이스 객체로 슬라이싱(slicing)하지 않도록 주의하세요. Swift 구조체는 클래스 상속 체인에 참여하지 않습니다. 이 예제는 하나의 특수화된 렌더러 레이블을 관찰합니다.

C++

전체 프로그램 파일: main.cpp.

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <optional>
#include <memory>
#include <tuple>
#include <variant>
#include <stdexcept>
#include <algorithm>
struct Renderer { virtual std::string style() const { return "full"; } virtual ~Renderer() = default; };
struct CompactRenderer final : Renderer { std::string style() const override { return "compact"; } };

int main() {
CompactRenderer compact;
    const Renderer &renderer = compact;
    std::cout << renderer.style() << '\n';
}

Swift

전체 프로그램 파일: Renderer.swift.

class Renderer { func style() -> String { "full" } }

전체 프로그램 파일: CompactRenderer.swift.

final class CompactRenderer: Renderer { override func style() -> String { "compact" } }

전체 프로그램 파일: main.swift.

let renderer: Renderer = CompactRenderer()
print(renderer.style())
challenge icon

챌린지

쉬움

init() 및 units의 2배를 반환하는 fee(units: Int) -> Int를 갖춘 Rate 클래스를 구현하세요. 기본 수수료에 5를 더하도록 fee를 오버라이드하는 서브클래스 RushRate를 구현하세요. 입력은 base 또는 rush 다음에 0부터 100까지의 units가 주어집니다. Rate 참조를 통해 인스턴스를 선택하고 그 fee를 출력하세요.

필요한 API와 solve(_ input: String) -> String을 구현하세요. 마지막 줄바꿈 없이 출력 텍스트를 반환하세요. 편집 가능한 코드 내에서 출력(print)하지 마세요. 잠긴 드라이버는 추가적인 유효한 입력에 대해 독립적으로 API를 검사한 후, 반환된 텍스트를 정확히 하나의 줄바꿈과 함께 출력합니다. 모든 수치 연산은 Int 범위 내에 유지됩니다.

작성한 코드는 Rate.swift, RushRate.swift, Functions.swift에 들어갑니다. main.swift는 제공된 입력/출력 코드를 담고 있으며 수정할 수 없습니다.

직접 해보기

import Foundation
func apiChecks(_ input: String) -> Bool {
let r: Rate = RushRate(); return r.fee(units: 7) == 19 && Rate().fee(units: 7) == 14 && r.fee(units: 0) == 5
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// 공개 API 프로브 시작
let apiOK = apiChecks(input)
// 공개 API 프로브 끝
if apiOK { print(solve(input)) } else { print("API mismatch") }
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

C++ 개발자를 위한 Swift의 모든 레슨

직접 연습해 보세요: Swift 플레이그라운드