c++ - 从基类成员函数返回派生类的实例

标签 c++ inheritance

可以吗?如果我从基类成员函数(使用 new Derived() 创建)返回 Derived 类的实例,请设计?

此外,这还涉及到需要转发声明派生类并使派生类构造函数公开。

代码示例:-

Class Base
{
 public:
  Base() {}
  Derived* get_new_derived(int X) 
  { 
    Derived *der = new Derived(X); 
    return der;  
  }
}

Class Derived : public Base
{
 private:
  int _X;
 protected:
  Derived(int X) { _X = X; }
 public:  
  Derived* get_new_derived(int X) 
  { 
    Derived *der = new Derived(X); 
    return der;  
  }
}

我还有一个派生类(比如 Derived1)。现在让我们说:-

用法1:

Derived1* der1 = new Derived1();
Derived * der = der1->get_new_derived(10);

用法2:

Derived1* der1 = new Derived1();
Base* bs = der1;
Derived * der = bs->get_new_derived(10);

最佳答案

在一般情况下,这通常表示设计不当 - 基类通常不应知道/关心其派生类。

请注意,您可以返回指向 Derived 的指针,类型为 Base* - 这就是工厂方法设计模式的原则。也许这符合您的实际情况?

但请注意,所有规则都有异常(exception)。如果您的(基类 + 派生类)表示一个紧密耦合且连贯的单元(例如具有两个子类 FastTreeSmallTreeTree 接口(interface),针对不同目的进行了优化),它们可以相互了解,Tree 定义如下函数:

std::unique_ptr<SmallTree> Tree::createSmallCopy() const
{
  return { new SmallTree(/*args*/) };
}

std::unique_ptr<FastTree> Tree::createFastCopy() const
{
  return { new FastTree(/*args*/) };
}

所以这取决于你的实际用例。我通常会对这种设计保持警惕,但它有其用途。


作为旁注,在现代 C++ 中,您永远不应该使用拥有原始指针 - 使用智能指针,如 std::unique_ptrboost::shared_ptr .

关于c++ - 从基类成员函数返回派生类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22141422/

相关文章:

c++ - 防止存储在内存中的字符串被其他程序读取

c++ - 这个简单的代码会导致内存泄漏吗?

C++程序设计

c++ - 返回派生类类型的基类中的方法?

c# - 如何使用基构造函数实例化继承类?

c++ - 在默认构造函数中可见的继承类的 c++ 计数器的实现

mysql - 我可以使用MySQL建立Symfony2 ORM继承关系吗?

c++ - 使用 sse intrinsics 的 (A)RGB32 图像最快 50% 缩放

c++ - 我怎样才能调用另一个类的方法?

c++ - 如何打印 n 维 C++ STL 容器?容器是数组的数组或 vector 的 vector