추상 기반 클래스 구현
출판물 계층 구조 설계:
// 추상 베이스 클래스
class Media {
public:
Media(const std::string &title = "") : title(title) {}
virtual ~Media() = default;
virtual void release() const = 0;
virtual void consume() const = 0;
protected:
std::string title;
};
// 도서 클래스
class Novel : public Media {
public:
Novel(const std::string &title, const std::string &writer)
: Media(title), writer(writer) {}
void release() const override {
std::cout << "도서 출간: 《" << title << "》 - " << writer << '\n';
}
void consume() const override {
std::cout << "독서 중: 《" << title << "》\n";
}
private:
std::string writer;
};
// 영화 클래스
class Movie : public Media {
public:
Movie(const std::string &title, const std::string &filmmaker)
: Media(title), filmmaker(filmmaker) {}
void release() const override {
std::cout << "영화 개봉: <" << title << "> - " << filmmaker << '\n';
}
void consume() const override {
std::cout << "영화 감상: <" << title << ">\n";
}
private:
std::string filmmaker;
};
연산자 오버로딩 구현
도서 판매 시스템:
// 도서 정보 클래스
class BookInfo {
public:
BookInfo(std::string title, std::string creator, std::string isbn, double cost)
: title(title), creator(creator), isbn(isbn), cost(cost) {}
friend std::ostream& operator<<(std::ostream &os, const BookInfo &item);
private:
std::string title;
std::string creator;
std::string isbn;
double cost;
};
// 출력 연산자 오버로딩
std::ostream& operator<<(std::ostream &os, const BookInfo &item) {
os << "제목: " << item.title << "\n저자: " << item.creator
<< "\nISBN: " << item.isbn << "\n가격: " << item.cost;
return os;
}
클래스 템플릿 활용
// 일반화 좌표 클래스
template<typename CoordinateType>
class Point {
public:
Point(CoordinateType x_val, CoordinateType y_val)
: x(x_val), y(y_val) {}
void show() const {
std::cout << x << ", " << y << '\n';
}
private:
CoordinateType x;
CoordinateType y;
};
// 템플릿 사용 예시
Point<int> int_point(5, 10);
Point<double> double_point(3.14, 2.71);
Point<std::string> text_point("East", "West");
가상 함수를 이용한 다형성
// 전자 애완동물 베이스 클래스
class DigitalPet {
public:
virtual ~DigitalPet() = default;
virtual std::string getName() const = 0;
virtual std::string makeSound() const = 0;
};
// 고양이 구현체
class VirtualCat : public DigitalPet {
public:
VirtualCat(std::string id) : id(id) {}
std::string getName() const override {
return id;
}
std::string makeSound() const override {
return "야옹~";
}
private:
std::string id;
};
템플릿을 이용한 복소수 클래스
template<typename NumericType>
class ComplexNumber {
public:
ComplexNumber(NumericType real_part, NumericType imag_part)
: real(real_part), imag(imag_part) {}
ComplexNumber& operator+=(const ComplexNumber& rhs) {
real += rhs.real;
imag += rhs.imag;
return *this;
}
friend std::ostream& operator<<(std::ostream& os, const ComplexNumber& num) {
if(num.imag >= 0)
os << num.real << " + " << num.imag << "i";
else
os << num.real << " - " << -num.imag << "i";
return os;
}
private:
NumericType real;
NumericType imag;
};