对指针的引用-多态性

Reference to a pointer - Polymorphism

本文关键字:多态性 引用 指针      更新时间:2023-10-16

如果我不是在将基指针发送给另一个类构造函数时使用对指针的引用- 在该类中将basepointer绑定到基的派生对象- basepointer返回NULL。

简单地说——这是什么原因?

#include <iostream>
using namespace std;
class Base {
   public:
      virtual void print() = 0;
};
class Sub1 : public Base {
public:
   void print() {
      cout << "I am allocated!n";
  }
};
class App {
public: 
   App(Base *b) {
      b = new Sub1;
   }
};
int main() {
   Base *b;
   b = NULL;
   App app(b);
   if (b != NULL)
      b->print();
   else
      cout << "Basepointer is NULLn";
   return 0;
}
这里的关键部分是app类构造函数的签名

当不使用对基指针的引用时,即

   App(Base *b)

输出为:

   Basepointer is NULL

当使用对基类的引用时,即

  App(Base *&b)

输出为:

 I am allocated!

您通过值传递指针,这意味着值被复制了,并且在函数中您只修改了副本。修改副本当然不会修改原始文件