typeid.name() not changing when iterating through a vector. Dynamic cast and typeid a base class pointer

前端 未结 2 1154
北海茫月
北海茫月 2021-01-21 11:53

Answer: In short use virtual functions! So don\'t actually use this as good design, but for learning purposes take a read!

I want to start off by saying I am using c++ a

2条回答
  •  鱼传尺愫
    2021-01-21 12:39

    This works as intended with doSomething as a virtual function. If it is not virtual, then the compilation itself will fail (if there are no other functions in the Shape class which are virtual). Dynamic cast will fail if source type is not polymorphic.

    If it is virtual, you need not do what you are doing to determine the type. Let polymorphism do its magic. You can shorten your code like this:

    #include 
    #include 
    
    class Shape { public: virtual void doSomething() {std::cout << "In Shape\n";}};
    class Circle: public Shape {public: void doSomething() {std::cout << "In Circle\n";}};
    class Square: public Shape {public: void doSomething() {std::cout << "In Square\n";}};
    
    int main() {
        std::vector vec;
        vec.push_back(new Square);
        vec.push_back(new Circle);
    
        for(auto tmp = vec.begin();tmp != vec.end(); ++tmp)
        {       
            (*tmp)->doSomething();        
        }
    }
    

提交回复
热议问题