C++在构造函数中更改类型?

标签 c++ class types polymorphism

我在头文件中有一个抽象类 Engine3D 及其结构(Vector3D 等)。

现在,我有了那个类的实现,ConcreteEngine3D : Engine3D。此外,我还有其他类,例如 ConcreteVector3D : Vector3D,它们具有将在 ConcreteEngine3D 中使用的其他成员和方法(为了这个示例,假设它是 浮点长度calculateLength())。

在 main.cpp 中我有代码:

#include "ConcreteEngine3D.h"
Engine3D * engine;
...
int main(){
    engine = new ConcreteEngine3D();
    Vector3D* vector = new Vector3D(engine, 10, 5, 2);
}

我希望变量 vector 的类型为 ConcreteVector3D*

我将在 ConcreteEngine3D 中需要那种类型,但在 main.cpp 中我什至不知道它是那种类型并且不必使用像 length 这样的扩展字段.此外,我不能在 main.cpp 中使用 ConcreteEngine3D.h 中的任何内容(仅 Engine3D.h)-这是为了灵活,更改实现必须意味着仅更改包含并与 new ConcreteEngine3D().

我不想修改上面的代码或 Engine3D 的原始 header 。

Vector3D 的构造函数中,我总是放置一个指向 Engine3D 对象的指针(我在这里给出 ConcreteEngine3D 类型)。

也许我可以在 Vector3D 的构造函数中做些什么来改变它的类型?

例如,在构造函数中调用 Vector3D* Engine3D::convert(Vector3D v),它将继承自 ConcreteEngine3D 中的 Engine3D (它使用 Vector3D 中的字段创建一个新的 ConcreteVector3D 对象并返回它)。

当然该代码不起作用:

Vector3D::Vector3D(Engine3D *engine){
    //how to 'return' or 'convert' the type to the one that returns engine->convert(this);
}

所以基本上,我想获得下面代码的效果,但没有 vector = engine->convert(vector)Vector3D* vector2 = new ConcreteVector3D(engine, 10, 5, 2)

#include "ConcreteEngine3D.h"
Engine3D * engine;
...
int main(){
    engine = new ConcreteEngine3D();
    Vector3D* vector = new Vector3D(engine, 10, 5, 2); //produces Vector3D, not ConcreteVector3D
    vector = engine->convert(vector); //cannot be here! but creates the right object
    Vector3D* vector2 = new ConcreteVector3D(engine, 10, 5, 2); //also creates rights object, but cannot be here!
}

此外,我不想在 Engine3DConcreteEngine3D 中使用工厂。我想让“用户”按照我在第一个代码中编写的方式创建 Vector3D

最佳答案

听起来您想使用抽象工厂模式来实例化您的对象,这样您就不必直接调用具体类的构造函数。然后,如果您想更改实现接口(interface)的具体类型,您只需要链接到抽象工厂的不同实现,或者在运行时选择合适的工厂实现。

编辑:错过了“不想使用工厂”...无论如何,您将需要某种重定向,因为构造函数将返回您实例化的类型。你能得到的最接近的可能是为类 Vector3D 创建一个静态工厂方法“create”,它返回一个指向 Vector3D 的指针,但在内部创建一个具体实现类的实例。如果您这样做,最好将 Vector3D 的构造函数设为私有(private),以防止以“错误的方式”创建 vector 。

关于C++在构造函数中更改类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11284268/

相关文章:

c++ - 查找由链表链接的数据的各个地址。 C++

c++ - 使用weak_ptr的观察者模式

c++ - 无法访问类中的公共(public)字段 | C++

function - F# 泛型/函数重载语法

types - Go中函数变量的类型

c++ - 如何在 CMakeList.txt 中链接 -ldl

c++ - 科学计算人员的异常与断言(我是我的代码的唯一用户)?

丢失属性的 Python 类

javascript - 可以重写此 Javascript 以用于类而不是 id 吗?

c - 数据类型独立堆栈 - C 编程