The slicing problemThe slicing problem
Posted at 2010. 11. 13. 02:14 | Posted in Computer#include <string> #include <iostream> using std::string; using std::cout; using std::endl; class Pet { public: string name; virtual void print() const; }; class Dog : public Pet { public: string breed; virtual void print() const; }; int main(int argc, char *argv[]) { Dog vdog; Pet vpet; vdog.name = "Tiny"; vdog.breed = "Great Dane"; vpet = vdog; cout << "The slicing problem:\n"; // vpet.breed;은 클래스 Pet이 breed라는 이름의 멤버를 가지지 않기 때문에 틀리다. vpet.print(); cout << "Note that it was print from Pet that was invoked.\n"; cout << "The slicing problem defeated:\n"; Pet *ppet; ppet = new Pet; Dog *pdog; pdog = new Dog; pdog->name = "Tiny"; pdog->breed = "Great Dane"; ppet = pdog; ppet->print(); pdog->print(); // 가상 함수를 통해서가 아닌 직접 멤버 변수에 접근하기 때문에 // 다음에서 에러가 발생한다. // cout << "name: " << ppet->name << " breed: " // << ppet->breed << endl; // 클래스 Pet은 breed라는 이름의 멤버를 가지지 않는다는 // 에러 메시지가 발생한다. return 0; } void Dog::print() const { cout << "name: " << name << endl; cout << "breed: " << breed << endl; } void Pet::print() const { cout << "name: " << name << endl; }
이 예제는 The slicing problem에 관한 것이다.
vdog.name = "Tiny";
vdog.breed = "Great Dane";
vpet = vdog;
vdog.breed = "Great Dane";
vpet = vdog;
vpet에는 breed가 없어 이렇게 하면 자료의 손실이 발생한다.
이것을 The slicing problem 이라고 부른다.
'Computer' 카테고리의 다른 글
Apple computer for sale: only $160K! (0) | 2010.11.13 |
---|---|
함수 템플릿 사용 예제 (0) | 2010.11.13 |
도메인 가치 평가 (0) | 2010.11.12 |
개발자의 뇌 구조 (0) | 2010.11.12 |
Visual Assist X 10.6.1833.0 Patch (0) | 2010.11.06 |