重载operator =和重载复制构造函数有什么区别? [英] What is the difference between overloading operator= and overloading the copy constructor?

查看:187
本文介绍了重载operator =和重载复制构造函数有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在类中重载 = 复制构造函数之间的区别是什么?





我的意思是,如果我有以下:

 人* p1 =新人(Oscar,Mederos); 
人* p2 = p1;

使用哪一个?



只是为了澄清一点:



我已经知道,如果我们显式调用复制构造函数 Person p1(p2),将使用复制构造函数。我想知道的是当使用每一个时,但是使用 = 运算符,而不是@Martin指向。

 解决方案

p1(Oscar,Mdderos);
人额外;

复制构造函数

 人员P2(p1); //使用复制构造函数复制
Person P3 = p2; //另一种形式的复制构造。
// P3正在初始化,它使用复制构造
//不是赋值运算符

作业:

  extra = P2; //已经存在的对象(extra)
//分配给。

值得一提的是,赋值运算符可以使用复制构造函数code>复制和交换 idium:

  class Person 
{
Person(std :: string const& f,std :: string const& s);
人(person const& copy);

//注意:不要在这里使用引用。
//因此得到一个隐式副本(使用复制构造函数)
//因此你只需要交换
Person& operator =(Person copy)
{
copy.swap(* this);
return * this;
}

void swap(Person& other)throws()
{
//交换其他成员和* this;
}
};


What is the difference between overloading the operator = in a class and the copy constructor?

In which context is each one called?

I mean, if I have the following:

Person *p1 = new Person("Oscar", "Mederos");
Person *p2 = p1;

Which one is used? And then when the other one is used?

Edit:
Just to clarify a little bit:

I already know that if we explicitly call the copy constructor Person p1(p2), the copy constructor will be used. What I wanted to know is when each one is used, but using the = operator instead, as @Martin pointed.

解决方案

In your case neither is used as you are copying a pointer.

Person p1("Oscar", "Mdderos");
Person extra;

The copy constructor

Person P2(p1);      // A copy is made using the copy constructor
Person P3  = p2;    // Another form of copy construction.
                    // P3 is being-initialized and it uses copy construction here
                    // NOT the assignment operator

An assignment:

extra = P2;         // An already existing object (extra)
                    // is assigned to.

It is worth mentioning that that the assignment operator can be written in terms of the copy constructor using the Copy and Swap idium:

class Person
{
    Person(std::string const& f, std::string const& s);
    Person(Person const& copy);

    // Note: Do not use reference here.
    //       Thus getting you an implicit copy (using the copy constructor)
    //       and thus you just need to the swap
    Person& operator=(Person copy)
    {
        copy.swap(*this);
        return *this;
    }

    void swap(Person& other) throws()
    {
          // Swap members of other and *this;
    }
};

这篇关于重载operator =和重载复制构造函数有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆