cpp_clone - 8BitsCoding/RobotMentor GitHub Wiki
Virtual Constructor(๋ถ์ . ๋ค์ด์บ์คํ ์์ ์๋ ํด๋์ค์๋ง ๊ตฌํ๋ ํจ์๊ฐ ํธ์ถ์ด ๋ ๊น?)
class Dog {
};
class YellowDog : public Dog {
};
void foo(Dog* d) {
Dog* c = new Dog(*d);
// ๋ณต์ฌ ์์ฑ์๊ฐ ํธ์ถ๋์ด์ c๋ Dog์ด ๋๋ค.
}
int main(){
YellowDog d;
foo(&d);
}
ํด๊ฒฐ์ฑ
class Dog {
public:
virtual Dog* clone() { return (new Dog(*this)); }
};
class YellowDog : public Dog {
public:
virtual YellowDog* clone() { return (new YellowDog(*this)); }
};
void foo(Dog* d) {
//Dog* c = new Dog(*d);
// ๋ณต์ฌ ์์ฑ์๊ฐ ํธ์ถ๋์ด์ c๋ Dog์ด ๋๋ค.
Dog* c = d->clone();
// c๋ YellowDog์ด ๋๋ค.
}
int main(){
YellowDog d;
foo(&d);
}
// VirtualContructor.cpp : ๊ธฐ๋ณธ ํ๋ก์ ํธ ํ์ผ์
๋๋ค.
#include "stdafx.h"
#include <stdio.h>
class Dog {
public:
virtual Dog* clone() { return (new Dog(*this)); }
virtual void printDog() {
printf("Dog \n");
}
};
class YellowDog : public Dog {
public:
virtual YellowDog* clone() { return (new YellowDog(*this)); }
void printDog() {
printf("Yellow Dog \n");
}
void printOnlyYellowDog() {
printf("Only YellowDog \n");
}
};
void foo(Dog* d) {
//Dog* c = new Dog(*d);
// ๋ณต์ฌ ์์ฑ์๊ฐ ํธ์ถ๋์ด์ c๋ Dog์ด ๋๋ค.
Dog* c = d->clone();
// c๋ YellowDog์ด ๋๋ค.
c->printDog();
// Yellow Dog ์ถ๋ ฅ
//c->printOnlyYellowDog();
// Compile Error
}
using namespace System;
int main(array<System::String ^> ^args)
{
YellowDog d;
foo(&d);
return 0;
}