为什么赋值运算符重载会创建对象的副本?

问题描述 投票:0回答:1

在下面给出的代码中,我已经在所有类构造函数,析构函数和重载的赋值运算符中编写了cout语句。

#include <iostream>
using namespace std;

class person {
    string name;
    int age ;
    int id ;
    static int num;
public :
    person (string name , int age) : name(name) , age(age) {
        id = num++;
        cout << "creating person : " << id << "(" << name <<")"<< endl;
    }
    person (const person &other) : name(other.name) , age(other.age) {
            id = num++;
            cout << "CREATING PERSON  : " << id << "(" << name <<")" << " from : " << other.id << endl;
    }
    ~person () {
        cout << "killing person : " << id << "(" << name <<")" << endl;
    }
    const person operator= (const person &other) {
        name = other.name ;
        age = other.age;
        //id = num++;
        cout << "copying in : " << id << "(" << name <<")" << " from : " << other.id << endl;
        return *this;
    }
    void print () {
        cout << "name : " << name << ", age : " << age << ", id : " << id << endl;
    }

int person::num = 1;
int main() {
    person per1 ("p1" , 20);
    person per2 ("p2" , 30);
    person per3 ("p3" , 40);
    cout << "see the strange object creation here: " << endl << endl;
    per3 = per2 = per1;
    return 0;
}

给定代码的输出结果是:

创建人:1(p1)

创建人:2(p2)

创建人:3(p3)

请参见此处的奇怪对象创建:

从:1复制:2(p1)

创建人:来自2的4(p1)

从:4复制:3(p1)

创建人:5(p1)来自:3

杀人:5(p1)

杀人:4(p1)

杀人:3(p1)

杀人:2(p1)

杀死人:1(p1)

我的问题是什么导致使用复制构造函数创建两个对象(4和5)?当分配中使用的对象已经存在时。有没有一种方法可以重载赋值运算符而不创建伪对象?因为此方法似乎不是非常优化。

c++ class operator-overloading copy-constructor
1个回答
1
投票

这是因为您的operator=()看起来像这样:

const person  operator= (const person &other)

即返回值。在这种情况下,const毫无意义。

您实际上的意思是改为通过常量引用返回:

const person& operator= (const person &other)

那个&会带来不同。

© www.soinside.com 2019 - 2024. All rights reserved.