å¤æ æ§
å¤æ æ§(ããªã¢ã¼ãã£ãºã )ã«ã¤ãã¦ãC++ã§ã¯æ¬¡ã®ãããªæé ã«ãªãã¾ãã
- 親ã¯ã©ã¹ã®ãã¤ã³ã¿ã«æ´¾çã¯ã©ã¹ã®ã¤ã³ã¹ã¿ã³ã¹ã®ãã¤ã³ã¿ã代å
¥ã
- Javaã¨åãã§ããã
- 親ã¯ã©ã¹ã®ã¡ã½ãããå®è¡âæ´¾çã¯ã©ã¹ã§ãªã¼ãã¼ã©ã¤ãããã¡ã½ãããå®è¡ãããã
- ãã®ã¨ãããªã¼ãã¼ã©ã¤ãããã¡ã½ããã¯ã親ã¯ã©ã¹ã§ãvirtualã修飾åãä»å ãã¦ããå¿ è¦ãããã¾ãã
- ãvirtualã修飾åãã¤ããªãã¨ããã¤ã³ã¿ã®æãã¤ã³ã¹ã¿ã³ã¹ãæ´¾çã¯ã©ã¹ã§ãã親ã¯ã©ã¹ã®ã¡ã½ãããå®è¡ããã¾ãã
#include <iostream> // 親ã¯ã©ã¹ class Animal { protected : char* name; public : Animal( char* name ); // æ´¾çã¯ã©ã¹ã§ãªã¼ãã¼ã©ã¤ãããé¢æ°ãvirtualãã¤ããã virtual void say(); }; Animal::Animal( char* name ){ this->name = name; } void Animal::say() { std::cout << "I'm animal "<< this->name << std::endl; } // æ´¾çã¯ã©ã¹1 class Kitten : public Animal { public : Kitten( char* name ); void say(); }; Kitten::Kitten(char* name ) : Animal( name ) { } void Kitten::say() { std::cout << "I'm kitten "<< this->name << std::endl; } // æ´¾çã¯ã©ã¹2 class Tiger : public Animal { public : Tiger( char* name ); void say(); }; Tiger::Tiger(char* name ) : Animal( name ) { } void Tiger::say() { std::cout << "I'm tiger "<< this->name << std::endl; } // ã¡ã¤ã³é¢æ° int main() { Kitten mii( "mii" ); Tiger tora( "tora" ); // 親ã¯ã©ã¹ã®ãã¤ã³ã¿ã // 親ã¯ã©ã¹ã®ãã¤ã³ã¿ã¾ãã¯ãããæ´¾çã¯ã©ã¹ã®ãã¤ã³ã¿ãä»£å ¥ã§ããã Animal* p = &mii; // ãã¤ã³ã¿ã®ç¤ºãã¤ã³ã¹ã¿ã³ã¹ã®ã¡ã½ãããå®è¡(ã->ã)æ¼ç®åã使ãã // æ´¾çã¯ã©ã¹ã§ãªã¼ãã¼ã©ã¤ãããã¡ã½ãããå®è¡ãããã p->say(); // I'm kitten mii p = &tora; p->say(); // I'm tiger tora return 0; }
å®è¡çµæã§ãã
I'm kitten mii I'm tiger tora