且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

多态 C++ 参考

更新时间:2023-02-12 12:21:22

没什么奇怪的.多态性适用于指针 引用:

There's nothing odd. Polymorphisms works both for pointers and references:

struct Base { };
struct Derived : Base;

void foo(Base &);

int main() {
  Derived x;
  foo(x);    // fine
}

您将此与另一个问题混为一谈,即创建对动态对象的引用:

You're conflating this with another issue, namely creating a reference to a dynamic object:

T * pt = new T;
T & rt = *pt;

T & x = *new T;  // same effect

请注意,通过引用跟踪动态对象通常是非常糟糕的样式,因为删除它的唯一方法是通过 delete &x;,它是很难看出 x 需要清理.

Note that it's generally very bad style to track a dynamic object only by reference, because the only way to delete it is via delete &x;, and it's very hard to see that x needs cleaning up.

您的设计有两种直接的选择:1) 使 a 成为 B 中的成员对象,或 2) 使 a 成为 shared_ptrunique_ptr 并将初始化器更改为 a(new A1).这完全取决于您是否真的需要多态行为,即您是否有 B 的其他构造函数将不同的派生类分配给 a 而不是 A1代码>.

There are two immediate alternatives for your design: 1) make a a member object in B, or 2) make a a shared_ptr<A> or unique_ptr<A> and change the initalizer to a(new A1). It all depends on whether you actually need the polymorphic behaviour, i.e. if you have other constructors for B which assign a different derived class to a other than A1.