【问题标题】:Construct sub class from other sub class从其他子类构造子类
【发布时间】:2018-06-07 09:46:44
【问题描述】:

我有以下类架构:

            Pokemon
              |
  --------------------------- ...  -------- ...
 |            |                         |
Bulbasaur     Charamander     ...     Ditto ...

我想从Ditto 的实例创建一个新的Pokemon 类,例如:

new Charamander(Ditto);

为此,我的想法是使用 super class 构造函数:

new Charamander(Pokemon);

PokemonDitto超类

但我不知道如何访问我的Ditto超级类 来提供Charamander 的构造函数。

【问题讨论】:

  • 有些语言可以通过猜测来学习。 C++ 不能。听起来像good C++ book 是为了。
  • C++中没有超类,主要是因为我们有多重继承。
  • 在决定如何使用它之前学习一个工具很重要。在这里,你反过来:在知道你能用它做什么之前选择你想如何使用 C++。不想变得粗鲁,但你在这里完全偏离了标准。 1/ 学习 C++。 2/ 扔掉所有东西。 3/ 重新开始。
  • 您可能会发现在类层次结构之外,在某种“游戏规则引擎”中管理和实现此类转换更容易。
  • @Ron 这是一个有趣的帖子。但是引用的书对我来说有点贵。你知道可以帮助我回答问题的免费在线书籍吗?

标签: c++ oop inheritance


【解决方案1】:

如果你想构造一个类的实例作为兄弟类的副本,那么我看到两个选项:

  1. 每个派生类都必须为每个兄弟类提供(复制?)构造函数。

  2. 每个派生类都必须提供一个构造函数,该构造函数从它们的公共超类复制。

后者听起来更好,因为它减少了要编写的代码量(并且以后可能会减少维护问题)。

当然,第三个选项是是否需要派生类。

但是,我为 2nd 选项做了一个小样本:

#include <iostream>
#include <string>

class Pokemon {
  private:
    static int _idGen;
  protected:
    int _id;
  public:
    Pokemon(): _id(++_idGen) { }
    Pokemon(const Pokemon&) = default;
    virtual const char* what() const = 0;
};

int Pokemon::_idGen;

class Ditto: public Pokemon {
  public:
    Ditto(): Pokemon()
    {
      std::cout << "Ditto created. (ID: " << _id << ")\n";
    }
    Ditto(const Pokemon &other): Pokemon(other)
    {
      std::cout << "Ditto cloned from " << other.what() << " (ID: " << _id << ").\n";
    }
    virtual const char* what() const override { return "Ditto"; }
};

class Charamander: public Pokemon {
  public:
    Charamander(): Pokemon()
    {
      std::cout << "Charamander created. (ID: " << _id << ")\n";
    }
    Charamander(const Pokemon &other): Pokemon(other)
    {
      std::cout << "Charamander cloned from " << other.what() << " (ID: " << _id << ").\n";
    }
    virtual const char* what() const override { return "Charamander"; }
};

int main()
{
  Charamander char1;
  Ditto ditto1;
  Charamander char2(ditto1);
  Ditto ditto2(char1);
  return 0;
}

输出:

Charamander created. (ID: 1)
Ditto created. (ID: 2)
Charamander cloned from Ditto (ID: 2).
Ditto cloned from Charamander (ID: 1).

Live Demo on coliru

对不起,如果我混合了口袋妖怪的。并不是说我对这些东西一无所知,只是有这个漫画系列(以及它周围的所有商品)......

关于免费的 C++ 书籍:您可以通过 google c++ book online 找到一些。如果您对质量有疑问,请改用 google good c++ book online...

【讨论】:

  • 很好的答案。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多