简体   繁体   中英

Assignment operator overload not getting called

I have two classes, Database and Record.

class Database {
    private:
        Record* head;
    public:
        Database(Record*);
        Database();
        Database(const Database&);

        Database& operator= (const Database &data);
};

class Record {
    public:
        Record(std::string, std::string, int, int, std::string);
        Record(const Record&);
        Record();

        Record* next;
};

Now when I do this

Database PM1, PM2;
//operations on PM1
PM2 = PM1;

All that happens is the values in PM1 are assigned to PM2. The assignment overload is never called. I have no idea as to why this may be happening. I've attempted to debug as well, but the function is just never entered. What am I doing wrong?

EDIT: Here's the overload function, it may not be right, but I haven't been able to test it yet because I can't even get it to run.

Database& Database::operator= (const Database &data) {
    if(this == &data)
        return *this;
    if(data.head == NULL) {
        this->head = NULL;
        return *this;
    }
    Record *curr1, *curr2;
    curr1 = new Record(*(data.head));
    this->head = curr1;
    for(curr2 = data.head->next; curr1 != NULL && curr2 != NULL; curr1 = curr1->next) {
        curr1->next = new Record(*curr2);
        curr2 = curr2->next;
    }
    return *this;
}

I think because you have pointer in your Database class and I guess you did not handle that you think you overloaded operator dose not work. You do shallow copy. so you need to handle that!

The objects may need to have been previously instantiated in order for the copy assignment function to be called.

// So instead of doing this:
Database PM1, PM2;
PM2 = PM1;

// Try this:
Database *PM1 = new Database();
Database *PM2 = new Database();
*PM2 = *PM1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM