what's polymorphic type in C++?

前端 未结 5 1257
猫巷女王i
猫巷女王i 2021-02-01 14:56

I found in one article saying \"static_cast is used for non-polymorphic type casting and dynamic_cast is used for polymorphic type casting\". I understand that int and double ar

5条回答
  •  一向
    一向 (楼主)
    2021-02-01 15:33

    First of all, the article is not completely correct. dynamic_cast checks the type of an object and may fail, static_cast does not check and largely requires the programmer to know what they're doing (though it will issue compile errors for some egregious mistakes), but they may both be used in polymorphic situations. (dynamic_cast has the additional requirement that at least one of the involved types has a virtual method.)

    Polymorphism in C++, in a nutshell, is using objects through a separately-defined interface. That interface is the base class, and it is almost always only useful to do this when it has virtual methods.

    However, it's rare-but-possible to have polymorphism without any virtual methods; often this is a sign of either bad design or having to meet external requirements, and because of that, there's no way to give a good example that will fit here. ("You'll know when to use it when you see it," is, unfortunately, the best advice I can give you here.)

    Polymorphism example:

    struct Animal {
      virtual ~Animal() {}
      virtual void speak() = 0;
    };
    
    struct Cat : Animal {
      virtual void speak() { std::cout << "meow\n"; }
    };
    
    struct Dog : Animal {
      virtual void speak() { std::cout << "wouf\n"; }
    };
    
    struct Programmer : Animal {
      virtual void speak() {
        std::clog << "I refuse to participate in this trite example.\n";
      }
    };
    

    Exercising the above classes slightly—also see my generic factory example:

    std::auto_ptr new_animal(std::string const& name) {
      if (name == "cat") return std::auto_ptr(new Cat());
      if (name == "dog") return std::auto_ptr(new Dog());
      if (name == "human") return std::auto_ptr(new Programmer());
      throw std::logic_error("unknown animal type");
    }
    
    int main(int argc, char** argv) try {
      std::auto_ptr p = new_animal(argc > 1 ? argv[1] : "human");
      p->speak();
      return 0;
    }
    catch (std::exception& e) {
      std::clog << "error: " << e.what() << std::endl;
      return 1;
    }
    

    It's also possible to use polymorphism without inheritance, as it's really a design technique or style. (I refuse to use the buzzword pattern here... :P)

提交回复
热议问题