éçããªã¢ã¼ãã£ãºã ã¨ã¿ã°ã»ãã£ã¹ããã
æè§ãªã®ã§ããã°ã©ãã³ã°ã®è¨äºãæ¸ãã¦ã¿ããã¨æãã
ããªã¢ã¼ãã£ãºã ã«ã¤ãã¦ã
ãã£ããè¨ãã¨ãååã®é¢æ°ãåãæå±ãã¦ããã¯ã©ã¹ã«ãã£ã¦æ¯ãèããå¤åããããã¨ã
ç¶æ¿ã«ãã£ã¦å®ç¾ã§ããã
#include <iostream> class Parent { public: virtual void Show() { std::cout << "Parent::Show" << std::endl; } }; class Child : public Parent { public: void Show() { std::cout << "Child::Show" << std::endl; } }; int main() { Parent* parentArray[5]; for(int i = 0; i < 4; i++) { parentArray[i] = i % 2 ? new Parent() : new Child(); } for(int i = 0; i < 4; i++) { parentArray[i]->Show(); } for(int i = 0; i < 4; i++) { delete parentArray[i]; } return 0; }
å®è¡çµæ
Child::Show Parent::Show Child::Show Parent::Show ç¶è¡ããã«ã¯ä½ããã¼ãæ¼ãã¦ãã ãã . . .
ããã¯ãå®è¡æã«ä»®æ³é¢æ°ãã¼ãã«ãä½æãããã¼ãã«ãåç §ãã¦ã©ã®é¢æ°ãå¼ã°ããã®ã決å®ããã®ã§ãä»®ã«åçããªã¢ã¼ãã£ãºã ã¨å¼ã¶ã
ããã«å¯¾ãtemplateãç¨ããããªã¢ã¼ãã£ãºã ã¯ã³ã³ãã¤ã«æã«æ±ºå®ãããã®ã§éçããªã¢ã¼ãã£ãºã ã¨å¼ã¶ã
ãã®å®ç¾æ¹æ³ã¯ãã¿ã°æ§é ä½ãç¨ãã¦ãã³ãã¬ã¼ãé¢æ°ããªã¼ãã¼ãã¼ãããã°è¯ãããã®æ¹æ³ãã¿ã°ã»ãã£ã¹ãããã¨å¼ã¶ã
#include <iostream> struct tag_int {}; struct tag_double {}; struct tag_char {}; struct tag_string {}; template<class T> void _print(const T& value, tag_int) { std::printf("%d\n", value); } template<class T> void _print(const T& value, tag_double) { std::printf("%f\n", value); } template<class T> void _print(const T& value, tag_char) { std::printf("%c\n", value); } template<class T> void _print(const T& value, tag_string) { std::printf("%s\n", value); } template<class T> void print(const T& value) { _print(value, T::tag()); } class Int { int value; public: operator int(){return value;} Int(int i) : value(i){} typedef tag_int tag; }; class Double { double value; public: operator double(){return value;} Double(double d) : value(d){} typedef tag_double tag; }; class Char { char value; public: operator char(){return value;} Char(char c) : value(c){} typedef tag_char tag; }; class String { const char* value; public: operator const char*(){return value;} String(const char* str) : value(str){} typedef tag_string tag; }; int main() { Int i(10); Double d(2.72); Char c('A'); String str("Hello"); print(i); print(d); print(c); print(str); return 0; }
å®è¡çµæ
10 2.720000 A Hello ç¶è¡ããã«ã¯ä½ããã¼ãæ¼ãã¦ãã ãã . . .
std::coutã§ã¯ãªã¼ãã¼ãã¼ãããæå³ãç¡ãã®ã§ãprintfã®ãã©ã¼ãããæå®åãå©ç¨ããã
å®éã«ã¯ãstd::advanceé¢æ°ã§ã渡ãããSTLã³ã³ããã®ã¤ãã¬ã¼ã¿ã®ç¨®é¡ã«ãã£ã¦ã¤ãã¬ã¼ã¿ã®é²ãæ¹(++ã++--ã+=ãï¼
ãå¤ãããããã®ã«ç¨ãããã¦ããã
åèæç®
εÏιÏÏημηãé«æ©ãæ¶ï¼"C++ãã³ãã¬ã¼ããã¯ããã¯"ãSoftBankCreativeï¼2009ï¼
"(void*)ãªãã¨"ï¼http://d.hatena.ne.jp/pknight/20100319/1268987210ï¼2012/6/14ã¢ã¯ã»ã¹ï¼
"Code++"ï¼http://ameblo.jp/woooh-p/entry-10036646454.htmlï¼2012/6/15ã¢ã¯ã»ã¹ï¼