[英]Copy constructor in C++ for later use in a function
I looked through different thread and I have a hard time understanding how to utilize copy constructor. 我浏览了不同的线程,并且很难理解如何利用副本构造函数。
If I want to manipulate my class, but I need to have original values to do so, I have to create a copy. 如果我想操纵我的班,但是我需要具有原始值,则必须创建一个副本。
class object {
public:
int member[5][5];
object(object&); <-- how do we create a copy here?
void manipulate() {
<<-- how do I call it here?
}
};
I've been trying different things such as object copy = object(object&)
but it does not work. 我一直在尝试不同的事情,例如
object copy = object(object&)
但是它不起作用。
object(object&); <-- how do we create a copy here?
One simple way is to omit the declaration, and let C++ compiler do it for you. 一种简单的方法是忽略该声明,然后让C ++编译器为您完成该声明。 Since your object does not allocate resources in its constructor's body, C++ can handle creating the copy constructor for you.
由于对象没有在其构造函数的主体中分配资源,因此C ++可以为您创建副本构造函数。
<<-- how do I call it here?
Like this: 像这样:
object copy(*this);
... // Manipulate it here
object( const object &obj )
{
for ( size_t i = 0; i < 5; i++ )
{
for ( int j = 0; j < 5; j++ )
{
member[i][j] = rhs.member[i][j];
}
}
}
Or you can write simply 或者你可以简单地写
object( const object &obj ) = default;
because your copy constructor does not do something special. 因为您的复制构造函数没有做任何特殊的事情。
As for its using then you may use it the following way 至于它的使用,那么您可以按以下方式使用它
object one;
onject two( one );
or 要么
object one;
onject two = one;
or even as 甚至
object one;
onject two { one };
or 要么
object one;
onject two = { one };
Also take into account that if you explicitly defined the copy constructor then you should explicitly define the default constructor if you need to have it. 还应考虑到,如果您明确定义了副本构造函数,则在需要时应明确定义默认构造函数。
A copy constructor is usually created because you cannot use the one generated by the compiler. 通常会创建一个副本构造函数,因为您不能使用编译器生成的副本构造函数。 In such a case, you will usually copy each member one by one.
在这种情况下,通常您将一个一个地复制每个成员。
For example (written on the fly - not sure if it would even compile with errors/warnings) 例如(即时编写-不确定它是否还会编译出错误/警告)
class A
{
public:
A();
A(const A& src)
{
m_array = (char*)new char[src.m_arraySize];
memcpy(m_array, src.m_array, src.m_arraySize);
m_arraySize = src.m_arraySize;
}
private:
char* m_array;
int m_arraySize;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.