c++ - 最佳实践 : A compose B, DerivedA compose DerivedB

标签 c++ coding-style

  • struct B 保存数据。
  • struct DerivedB:B 将一些特定数据添加到 B
  • A 类持有对 B 类型对象的引用。
  • DerivedA 类持有对 DerivedB 类型对象的引用。

它本质上是一个糟糕的设计吗?

如果不是,实现该目标的最佳方法是什么?

class A
{
public:
    A() :m_b(std::make_unique<B>(B())) {}
    B& getB() { return *m_b; }
protected:
    A(std::unique_ptr<B> b):m_b(std::move(b)) {}
private:
    std::unique_ptr<B> m_b;
};

class DerivedA : public A
{
public:
    DerivedA() :A(std::make_unique<B>(DerivedB())) {}
    DerivedB& getDerivedB() { return static_cast<DerivedB&>(getB()); }
};

这个使用强制转换的解决方案是最好的吗?

最佳答案

Is it inherently a bad design?

是的,向下转换通常被认为是 C++ 中的一种设计味道。它通常是一个标志,表明您的设计正在打破 Liskov substitution principle . 而是考虑对 BDerivedB 使用多态性来实现所需的行为。

关于c++ - 最佳实践 : A compose B, DerivedA compose DerivedB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41877995/

相关文章:

HTML5 NAV 与 HEADER 排序

android - 编码风格 : Two activities with moSTLy same code but different content view

c++ - 检测 C++ 代码样式问题的工具?

c++ - 读取超出 istringstream 字符串末尾的内容。

c++ - 什么时候将对象值添加到堆上的 vector 是安全的?

c++ - 加载 bmp 文件到 HBITMAP

c++ - TCP Socket block 函数段错误,由移动 if 语句引起

java - 我应该如何将功能划分为 Java 类?

objective-c - 在 Obj-C 中过度使用点运算符的替代方法是什么?

c++ - Eclipse CDT 调试配置存储在哪里?