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 |
Class를 이용한 18자리의 Int 자료형 구현Class를 이용한 18자리의 Int 자료형 구현
Posted at 2010. 11. 12. 13:21
보호되어 있는 글입니다.
내용을 보시려면 비밀번호를 입력하세요.
030. 캐스트 연산자 이해하기030. 캐스트 연산자 이해하기
Posted at 2010. 11. 12. 03:21 | Posted in Computer/초보자를 위한 C 언어 300제#include <stdio.h>
main()
{
int x = 5, y = 2;
printf( "%d \n", x / y ); // 2
printf( "%f \n", (double)x / y ); // 2.500000
}
'Computer > 초보자를 위한 C 언어 300제' 카테고리의 다른 글
| 032. 중첩 조건문 이해하기(if~else) (0) | 2010.11.13 |
|---|---|
| 031. sizeof 연산자 이해하기 (0) | 2010.11.13 |
| 029. 비트 연산자 이해하기(|, &, ~, ^, <<, >>) (0) | 2010.11.12 |
| 028. 쉼표 연산자 이해하기(,) (0) | 2010.11.12 |
| 027. 조건 연산자 이해하기(?:) (0) | 2010.11.12 |
