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;
}
โš ๏ธ **GitHub.com Fallback** โš ๏ธ