ç¶æ¿ ãã®2
ç¶æ¿ã®ã¤ã¥ããã¡ã½ããã¨ã³ã³ã¹ãã©ã¯ã¿ã®ãªã¼ãã¼ã©ã¤ãã«ã¤ãã¦ã
ã¡ã½ããã®ãªã¼ãã¼ã©ã¤ã
æ®éã«ã§ãã¾ããç¹ã«æ¸ããã¨ãªãããªã¼ãã¼ã©ã¤ããã親ã¯ã©ã¹ã®ã¡ã½ãããå¼ã³åºãã«ã¯ã<親ã¯ã©ã¹å>::ããã¤ãã¾ããJavaã®ãsuper.ãã®ãããã®ã
#include <iostream> // 親ã¯ã©ã¹ class Animal { protected : // protected ã¾ãã¯publicã¨ãããã¨ã void run(); }; void Animal::run() { std::cout << "animal run." << std::endl; } // æ´¾çã¯ã©ã¹ class Kitten : public Animal { public : // ãªã¼ãã¼ã©ã¤ãããå ´åããããã¿ã¤ã宣è¨ã¯å¿ è¦ã void run(); }; // ãªã¼ãã¼ã©ã¤ããããé¢æ° void Kitten::run() { // 親ã¯ã©ã¹ã®ã¡ã½ããå¼ã³åºã // ã親ã¯ã©ã¹å::ããã¤ããã Animal::run(); std::cout << "kitten run." << std::endl; } // ã¡ã¤ã³é¢æ° int main() { Kitten kitten; kitten.run(); return 0; }
å®è¡çµæã§ãã
animal run. kitten run.
親ã¯ã©ã¹ã®ã³ã³ã¹ãã©ã¯ã¿ã®å¼ã³åºã
Javaã¨åãããæ´¾çã¯ã©ã¹ã®çææã«ã¯è¦ªã¯ã©ã¹ã®ã³ã³ã¹ãã©ã¯ã¿ãå®è¡ããå¿ è¦ãããã¾ãã
- 親ã¯ã©ã¹ã§å¼æ°ãªãã®ããã©ã«ãã³ã³ã¹ãã©ã¯ã¿ãå®ç¾©ããã¦ããå ´åãæé»çã«ãããå®è¡ããã¾ãã(Javaã¨åã)
- å¼æ°ããã®ã³ã³ã¹ãã©ã¯ã¿ãå®è¡ãããå ´åãæ´¾çã¯ã©ã¹ã®ã³ã³ã¹ãã©ã¯ã¿ã«ã: <親ã¯ã©ã¹ã®ã³ã³ã¹ãã©ã¯ã¿>(<å¼æ°..>)ãã追å ãã¾ãã
- javaã®ããã«ãsuper(<å¼æ°>);ãã§å®è¡ã§ãããã¯ãã¾ããã
#include <iostream> // 親ã¯ã©ã¹ class Animal { public : Animal( ); Animal( char* name ); }; // 親ã¯ã©ã¹ã®ã³ã³ã¹ãã©ã¯ã¿ãå¼æ°ãæ㤠Animal::Animal(char* name) { std::cout << "animal " << name << " created." << std::endl; } // 親ã¯ã©ã¹ã®ããã©ã«ãã³ã³ã¹ãã©ã¯ã¿ Animal::Animal() { std::cout << "animal created." << std::endl; } // æ´¾çã¯ã©ã¹ class Kitten : public Animal { public : Kitten( ); Kitten( char* name ); }; // æ´¾çã¯ã©ã¹ã®ã³ã³ã¹ãã©ã¯ã¿ Kitten::Kitten( char* name ) : Animal( name ) { // 親ã¯ã©ã¹ã®å¼æ°ã¤ãã³ã³ã¹ãã©ã¯ã¿ãå®è¡ããè¨å® std::cout << "kitten " << name << " created." << std::endl; } // æ´¾çã¯ã©ã¹ã®ããã©ã«ãã³ã³ã¹ãã©ã¯ã¿ Kitten::Kitten() { std::cout << "kitten created." << std::endl; } // ã¡ã¤ã³é¢æ° int main() { Kitten kitten; Kitten kitten2( "mii" ); return 0; }
å®è¡çµæã§ãã
animal created. kitten created. animal mii created. kitten mii created.