추상 기반 계약
Coddy의 PHP 개발자를 위한 C++ 코스 레슨. 48개 중 40번째.
PHP 인터페이스와 추상 클래스는 C++의 기반 클래스처럼 명목적입니다. 클래스는 implements 또는 extends를 선언해야 하며, Renderer 형식으로 지정된 매개변수는 일치하는 메서드만 가진 객체를 거부하지만, 런타임에 TypeError가 발생할 때만 그렇게 합니다. 형식을 지정하지 않은 PHP 코드는 여전히 올바른 메서드를 가진 모든 객체를 허용합니다. C++ 추상 기반 클래스는 순수 가상 함수를 사용하며 명시적 상속이 필요합니다. 메서드 이름만 일치한다고 해서 이런 관계가 성립하지는 않으며, 프로그램이 실행되기 전에 컴파일러가 불일치를 거부합니다.
PHP
<?php
interface Renderer {
public function render(string $text): string;
}
class Plain implements Renderer {
public function render(string $text): string {
return $text;
}
}
class Bracketed implements Renderer {
public function render(string $text): string {
return "[" . $text . "]";
}
}
function show(Renderer $r): void {
echo $r->render("hi"), "\n";
}
foreach ([new Plain(), new Bracketed()] as $r) {
show($r);
}
C++
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
struct Shape{virtual ~Shape()=default;virtual std::string name()const=0;};struct Square:Shape{std::string name()const override{return "square";}};
int main(){
Square x;const Shape& s=x;std::cout<<s.name()<<"\n";
}
각 프로그램을 독립적으로 추적하세요. 이 예제들은 과제와 다른 연산이나 데이터를 사용해 개념을 보여 줍니다. 소스 코드의 출력과 대상 코드의 출력이 일치한다고 가정하지 마세요.
챌린지
쉬움입력: 텍스트 한 줄입니다. Channel은 순수 가상 함수 send와 가상 소멸자를 선언합니다. Plain은 텍스트를 반환하고, Tagged는 태그, 콜론, 텍스트를 차례로 반환합니다. 드라이버는 태그가 log인 Plain과 Tagged를 차례로 출력합니다.
편집 가능한 모듈: Channel.cpp, Channel.hpp, Plain.cpp, Plain.hpp, Tagged.cpp, Tagged.hpp. 필요한 각 형식에는 이름이 지정된 헤더와 구현 파일이 있습니다. 모든 공개 시그니처를 그대로 유지하세요. 잠금 처리된 main.cpp는 stdin을 읽고 API를 직접 호출합니다. 또한 명시된 경우 공개 API의 동작을 독립적으로 확인합니다. API 내부에서 출력하지 말고 반환값을 사용하세요. 정수 입력과 결과는 부호 있는 int 범위에 들어가며, 별도 언급이 없다면 텍스트는 ASCII입니다.
직접 해보기
#include "Channel.hpp"
#include "Plain.hpp"
#include "Tagged.hpp"
#include <iostream>
int main(){
{Plain p;Tagged t("warn");const Channel& a=p;const Channel& b=t;if(a.send("probe")!="probe"||b.send("other")!="warn:other")return 21;}
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
Plain a;Tagged b("log");std::string s=rows.empty()?"":rows[0];for(const Channel* p:std::vector<const Channel*>{&a,&b})std::cout<<p->send(s)<<"\n";
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
PHP 개발자를 위한 C++의 모든 레슨
직접 연습해 보세요: 온라인 C++ 컴파일러