重载operator =和重载构造函数重载有什么区别?

Osc*_*ros 9 c++ operator-overloading copy-constructor

重载=类中的运算符和复制构造函数之间有什么区别?

在哪个上下文中被称为?

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

Person *p1 = new Person("Oscar", "Mederos");
Person *p2 = p1;
Run Code Online (Sandbox Code Playgroud)

使用哪一个?然后当使用另一个?

编辑:
只是澄清一下:

我已经知道如果我们显式调用复制构造函数Person p1(p2),将使用复制构造函数.我想知道的是当每个人都使用时,而是使用=运算符,正如@Martin指出的那样.

Mar*_*ork 12

在你的情况下,你没有使用复制指针.

Person p1("Oscar", "Mdderos");
Person extra;
Run Code Online (Sandbox Code Playgroud)

复制构造函数

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
Run Code Online (Sandbox Code Playgroud)

作业:

extra = P2;         // An already existing object (extra)
                    // is assigned to.
Run Code Online (Sandbox Code Playgroud)

值得一提的是,赋值运算符可以使用Copy and Swapidium 以复制构造函数的形式编写:

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;
    }
};
Run Code Online (Sandbox Code Playgroud)


Ker*_* SB 5

复制构造函数是一个构造函数,它创建一个对象.特别是,复制构造函数创建一个对象,该对象在语义上与另一个已经存在的对象相同,并且它对其进行"复制":

Person newperson(oldperson); // newperson is a "copy" of oldperson
Run Code Online (Sandbox Code Playgroud)

赋值运算符根本不是构造函数,而是只能在现有对象上调用的普通成员函数.它的目的是为你的对象分配另一个对象的语义,这样在赋值之后两者在语义上是相同的.您通常不会"重载"赋值运算符,您只是定义它.

Person p;          // construct new person
/* dum-dee-doo */
p = otherperson;   // assign to p the meaning of otherperson, overwriting everything it was before
                   // invokes p.operator=(otherperson)
Run Code Online (Sandbox Code Playgroud)

请注意,如果与对象(with ==)进行比较是有意义的,那么复制构造和赋值都应该表现得如下:

Person p1(p2);
assert(p1 == p2);

p1 = p3;
assert(p1 == p3);
Run Code Online (Sandbox Code Playgroud)

您没有被迫保证这一点,但是您的类的用户通常会采取这种行为.实际上,编译器假设Person p1; Person p2(p1);需要p1 == p2;.

最后,作为最后的一边,如其他地方所说的那样,请注意Person p = p2; 字面意思Person p(p2)(复制构造),而不是 Person p; p = p2;.这是一种语法糖,允许您在不影响效率的情况下编写自然的代码(甚至是正确性,因为您的类甚至可能不是默认构造的).