需要复制构造函数 [英] Need of copy constructor
问题描述
您好,专家,
我对以下两种情况感到困惑.
Context1://复制构造函数
Hi Experts,
I am little confusing over the following two situations.
Context1://Copy Constructor
class A
{
public:
int aVar;
A(int tmp)
{
aVar=tmp;
}
A(A *ptr)//copy constructor part
{
aVar=ptr->aVar;
}
};
int main()
{
A a(10),b(&a);
}
Context2://与复制构造函数相同的结果
Context2://Same result of copy constructor
class A
{
public:
int aVar;
A(int temp)
{
aVar=temp;
}
A()
{
}
};
int main()
{
A a(10),b;
b=a;//just like a copy constructor
}
我认为不需要解释代码.在第一种情况下,我使用的是复制构造函数.在第二种情况下,我只是将第二个对象(b)分配给第一个对象(a).如果是这种情况,那么为什么我们需要复制构造函数?请帮我..
谢谢与问候
Arun
I think no need of explanation for the code is required. In the first case I am using a copy constructor. In the second case I am just assigning the second object(b) to first object(a). If this is the case, then why we required copy constructors? Please help me on this..
Thanks and Regards
Arun
推荐答案
在第二种情况下,如果不指定复制构造函数,则编译器将使用默认的构造函数来对对象进行浅表复制.
附言副本构造函数被声明为对相同类的常量对象的引用
In the second case, if you don''t specify a copy constructor the compiler uses a default one which makes a shallow copy of the object.
Ps. a copy constructor is declared as a reference to a constant object of the same class
A(const A& a);
-Robotex
-Robotex
实际上,在第二种情况下,您正在使用赋值运算符.同样,就像复制构造函数一样,如果您不编写赋值运算符,则编译器将为您生成一个.编译器生成的赋值运算符将如下所示:
Actually in the second case, you are using the assignment operator. Again, just like the copy constructor, if you do not write an assignment operator then the compiler will generate one for you. The compiler generated assignment operator will be like the following:
ClassA& operator=(const ClassA& rhs)
{
aVar = rhs.aVar;
return *this;
}
无论何时写
Whever you write
class A
{
int m;
};
编译器会执行
The compiler will do
class A
{
int m;
public:
A() :m() {}
A(const A& a) :m(a.m) {}
A& operator=(const A& a) { m=a.m; return *this; }
~A() {}
};
因此,除非您将其中一个或所有功能明确声明为私有功能,否则类似
a1 = a2;
return a;
fn(a);
将始终隐式解析为编译器生成的默认值.
有人认为,如果不存在这样的自动生成的东西"会更好,但是通过这种方式,旧的C99 struct
无法复制.
hence, unless you explicitly declare one or all of those function as private, things like
a1 = a2;
return a;
fn(a);
will always implicitly resolve to the compiler generated default.
There is people who think it would be better if such "autogenerated things" woludn''t be there, but this way, an old C99 struct
cannot copy.
这篇关于需要复制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!