[c++] 같은 클래스를 상속받은 서로 다른 클래스의 객체들을 배열처럼 묶을 수 있나요?
조회수 1868회
A라는 클래스를 B,C,D가 상속 받았습니다 그리고 B,C,D의 객체들을 배열처럼 묶을 수 있나요? arr[0]=B 객체 arr[1]=C 객체 arr[2]=D 객체 이런식으로 인덱스에 접근도 가능하게 할 수 있나요?
2 답변
-
-
상속받은 클래스들을 하나의 배열에서 관리하기 위해서는 부모의 타입으로 변환하여 사용하는 방법이 있습니다.
#include <iostream> #include <memory> struct A { virtual ~A() {} virtual void print() { std::cout << "A" << std::endl; } }; struct B : public A { void print() { std::cout << "B" << std::endl; } }; struct C : public A { void print() { std::cout << "C" << std::endl; } }; int main() { A* array[] = { new B , new C }; for (std::size_t i = 0, size = sizeof(array) / sizeof(array[0]); i < size; ++i) array[i]->print(); for (std::size_t i = 0, size = sizeof(array) / sizeof(array[0]); i < size; ++i) delete array[i]; return 0; }
위 방법은 메모리를 직접 관리해 줘야하기 때문에 불편함이 있습니다. 여기서 스마트 포인터를 적용하면 아래와 같습니다.
#include <iostream> #include <memory> struct A { virtual ~A() {} virtual void print() { std::cout << "A" << std::endl; } }; struct B : public A { void print() { std::cout << "B" << std::endl; } }; struct C : public A { void print() { std::cout << "C" << std::endl; } }; int main() { std::unique_ptr<A> array[] = { std::unique_ptr<B>(new B) , std::unique_ptr<C>(new C) }; for (std::size_t i = 0, size = sizeof(array) / sizeof(array[0]); i < size; ++i) array[i]->print(); return 0; }
댓글 입력