用不同的构造函数重新分配对象

Reassign object with different constructor

本文关键字:分配 对象 新分配 构造函数      更新时间:2023-10-16

MyClass类中,我有一个成员Dialog dialog_

MyClass的构造函数被调用后,我想用MyClass的构造函数中创建的参数为dialog_调用一个不同的构造函数(这就是为什么我不能直接调用dialog_的不同构造函数,而只是默认的构造函数)。

所以我试了

dialog_ = Dialog(/* different constr. w/ parameters passed from MyClass */);

但这不起作用。错误是

Error: no operator "=" matches these operands
operand types are: Dialog = Dialog

所以我谷歌了一下,发现在这个线程So(第3个答案)一个代码片段,我尝试:

dialog_.~Dialog();
new(&dialog_) Dialog(/* different constr. w/ parameters passed from MyClass */);

它起作用了。线程中的答案虽然状态"这个值并不超出纯粹的理论。不要在实践中这么做。"

那么,我能做些什么来解决我的问题,而不使用这段明显令人皱眉的代码呢?

我希望你能理解我想达到的目的。谢谢!

有两种方法可以实现你想要的。

在c++98中,您需要将一些初始化延迟到从构造函数调用的init()函数中。这有点棘手,因为这意味着对许多成员变量进行冗余构造和赋值。

在c++11中,你可以在初始化列表中调用另外一个构造函数,传递计算值(这些值可以在静态函数中计算)。

如果你提供一个构造函数代码的例子,我可以告诉你怎么做。

您可以将Dialog成员放在std::unique_ptr中,然后在需要时替换它:

class MyClass {
private:
    std::unique_ptr<Dialog> dialog_;
public:
    MyClass():
        dialog_( /* ... first constructor ... */ ) {}
    void setNewDialog(/* parameters */) {
        dialog_.reset(new Dialog(/* parameters */) );
    }
};

我试过的都没用,所以我就用

dialog_.~Dialog();
new(&dialog_) Dialog(/* ... */);

尽管它很糟糕