【问题标题】:Return a subclass in constructor Method在构造方法中返回子类
【发布时间】:2013-10-30 18:25:39
【问题描述】:

我有一个基类,当我调用构造函数时,它会根据配置访问系统并返回它的子类。 主要思想和类是抽象他自己的工厂,根据配置系统,根据需要返回子类。

我用 C++ 将我的想法表达为草稿,不一定是针对他的特定内容,而是针对其他语言(如 java 等)的通用方法。

有可能吗?

例子:

class system {
    public:
        Config config;
}

class Base {
    public:
        Base() {
            if(System.getInstance().config == Config.FooMode) {
                Foo foo = new Foo();
                return foo;
            }
        };
};

class Foo: public Base {
    public:
        float a;
        float b;
        float c;
}

class Boo: public Base {
    public:
        float d;
        float f;
        float g;
}

int main() {
    Point point = new Point();
    return 0;
}

【问题讨论】:

  • 改用factory method
  • 构造函数不会在 C++ 或 Java(或 C# 中)返回。

标签: java c++ algorithm design-patterns constructor


【解决方案1】:

不可能。构造函数不返回任何内容,使用另一种方法作为factory 方法。

class Base
{
  Foo makeFoo()
  {
  }
  ...
};

我混淆了你的代码是 C++ 还是 Java,所以不知道我应该使用什么代码。

【讨论】:

    【解决方案2】:

    您可能需要复习基本的 OO 概念。 Constructors 不返回任何东西。好吧,从某种意义上说,它们确实返回了classinstance,但是您不能将任何return 类型与constructors 一起使用。甚至没有void。为什么 ?阅读THIS

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多