本文介绍了需要复制构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,专家,

我对以下两种情况感到困惑.

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

推荐答案

A(const A& a);



-Robotex



-Robotex


ClassA& operator=(const ClassA& rhs)
{
  aVar = rhs.aVar;
  return *this;
}


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.


这篇关于需要复制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 13:54