对于C ++的复制和赋值构造函数,我仍然有些犹豫。到目前为止,我所拥有的是A.hpp
:
class A {
private:
char* str;
public:
A(char* str);
// strcpy str from other to this.
A(const A& other);
// free str in this, and strcpy str from other to this.
A& operator=(const Type& other);
}
假设我有能力A* a = new A(some_char_str);
,我会写作A b = *a;
,并且b
是的深层副本a
。现在的问题是我想要编写代码的能力。A* b = new A(a);
那么,我如何指定一个构造函数,该构造函数需要一个指针A
并A
在堆上创建一个新的呢?
噢,好吧,脑子屁……我刚刚意识到我A::A(const A* other)
自己可以提供一个构造函数,而无需使用复制/分配构造函数,也可以A* b = new A(*a);
按照注释中的建议进行编写。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句