Menu
CoddyTech

가상 디스패치

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

Luau의 모든 메서드 호출은 런타임에 테이블을 조회합니다. child:label()은 인스턴스를 조회한 다음 __index를 따라 Child로 이동하고 이어서 Base로 이동하므로, 재정의는 체인에서 더 앞서 발견되는 키일 뿐입니다. super 키워드는 없습니다. 재정의된 메서드는 Base.label(self)을 명시적으로 호출합니다. C++에서는 virtual이 필요하며 기본 클래스 값을 사용할 때 슬라이싱이 발생하지 않도록 해야 합니다. 기본 클래스 포인터나 참조를 통한 C++의 virtual 호출은 동적으로 디스패치됩니다. 다형성 객체를 삭제하려면 가상 소멸자가 필요하며, 기본 클래스 값으로 복사하면 슬라이싱이 발생할 수 있습니다.

Luau

local Base = {}
Base.__index = Base
function Base:label()
    return "base"
end
local Child = setmetatable({}, {__index = Base})
Child.__index = Child
function Child.new()
    return setmetatable({}, Child)
end
function Child:label()
    return Base.label(self) .. "!"
end
print(Child.new():label())

C++

#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
struct Sound{virtual ~Sound()=default;virtual std::string play()const{return "tap";}};struct Chime:Sound{std::string play()const override{return "ding";}};
int main(){
Chime x;const Sound& s=x;std::cout<<s.play()<<"\n";
}

각 프로그램을 독립적으로 추적해 보세요. 이 예제들은 과제와 다른 연산이나 데이터를 사용해 개념을 보여 줍니다. 소스와 대상의 출력이 일치한다고 가정하지 마세요.

challenge icon

챌린지

쉬움

입력값은 기본 요금과 보너스이며, 둘 다 음수가 아닙니다. Fee.amount는 기본 요금을 반환합니다. ExtraFee는 Fee를 공개 상속하고, amount를 재정의하여 보너스를 더합니다. 드라이버는 const Fee 참조를 통해 호출합니다. 가상 소멸자를 사용하세요.

편집 가능한 모듈: Fee.cpp, Fee.hpp, ExtraFee.cpp, ExtraFee.hpp. 각 필수 타입에는 고유한 이름의 헤더와 구현 파일이 있습니다. 모든 공개 시그니처를 유지하세요. 잠긴 main.cpp는 표준 입력을 읽고 API를 직접 호출합니다. 또한 명시된 경우 공개 API 동작을 별도로 검사합니다. API 내부에서 출력하지 말고 값을 반환하세요. 정수 입력값과 결과는 부호 있는 int의 범위에 들어갑니다. 별도 언급이 없는 한 텍스트는 ASCII입니다.

직접 해보기

#include "Fee.hpp"
#include "ExtraFee.hpp"
#include <iostream>
int main(){
{Fee a(5);ExtraFee b(2,7);const Fee& r=b;if(a.amount()!=5||r.amount()!=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 a,b;in>>a>>b;ExtraFee f(a,b);const Fee& ref=f;std::cout<<ref.amount()<<"\n";
}
quiz icon실력 점검

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

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

직접 연습해 보세요: 온라인 C++ 컴파일러