【问题标题】:why we to use base pointer to operate on derive class member when we can do it using derive class pointer itself at compile time? [duplicate]为什么我们可以在编译时使用派生类指针本身来操作派生类成员? [复制]
【发布时间】:2020-12-12 00:36:52
【问题描述】:

************************ 这里我可以在编译时使用 Derive pinter ************ **** **** 运行时多态性也较慢 *******************************

    #include <iostream> 
    using namespace std; 
    class base { 
        public: 
        virtual void print() 
        { 
            cout << "print base class" << endl; 
        } 
    
        void show() 
        { 
            cout << "show base class" << endl; 
        } 
    }; 
    class derived : public base { 
    public: 
        void print() 
        { 
            cout << "print derived class" << endl; 
        } 
       void show() 
        { 
            cout << "show derived class" << endl; 
        } 
    }; 
    
int main() 
    { 
        base* bptr; 
        derived d; 
        bptr = &d; 
    
        // virtual function, binded at runtime 
        bptr->print(); 
      //binded at compile time 
        derived *dptr =&d; 
        dptr->print();
    } 

【问题讨论】:

标签: c++


【解决方案1】:

在您的代码中使用 base*derived* 没有区别,因为这是一个几乎什么都不做的示例。

在实际应用程序中,人们使用基类指针可以灵活地交换不同的派生类,而无需更改调用者的代码。请参阅:polymorphism 了解更多信息。

另见此示例:

class Animal {
  virtual void eat() = 0;
}
class Cat : public Animal {
  void eat();
}
class Dog : public Animal {
  void eat();
}
int main() {
  Cat cat;
  Dog dog;
  std::vector<Animal *> animals= {&cat, &dog};
  for (Animal *animal : animals) {
    animal->eat();
  }
}

这里,我们依靠基类指针(Animal *)的使用,在不同的派生类中调用eat()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-06
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-21
    • 2014-12-05
    相关资源
    最近更新 更多