用不同的构造函数重新分配对象
Reassign object with different constructor
在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(/* ... */);
尽管它很糟糕
相关文章:
- 使用操作重载对象重新分配对象
- 静态分配对象的值初始化
- C++ 将抽象类型的动态分配对象传递给函数并存储在向量中
- 堆分配对象中的堆栈对象在 c++ 中在哪里分配?
- 在 c++ 的构造函数中分配对象向量时出错
- 动态分配对象中的字段-动态分配更好还是静态分配更好?C++
- 操作后通过运算符分配对象
- 如何捕获源自静态分配对象的构造函数的异常?
- 在C++中,当重新分配对象时,为什么构造函数在析构函数之前触发?
- 如何使用每个对象的单个构造函数参数动态分配C++对象数组?
- 将动态分配对象传递到 boost::any 构造函数中
- 混合指向已分配对象和作用域对象的指针
- C 删除指向动态分配对象的指针
- 有关动态分配对象的问题
- 类的堆分配对象是否在其作用域之后但在 C++ 中调用其析构函数之前处于活动状态
- C++ 中的黑白堆分配对象和堆栈分配对象的性能差异
- 是隐式创建的默认构造函数,负责分配对象内存
- 如何删除用于动态分配对象的智能指针
- 分配对象数组时如何初始化每个对象
- 用于堆栈分配对象的C++虚拟析构函数内联