简体   繁体   中英

Using objects as the key and value in c++ maps

I've got a class called Transaction_List.cpp which is supposed to map objects from two other classes. One of the other classes is Date.cpp which holds a date and time (EX: 1/29/2018 12:34:56) and a class Transactions.cpp which holds a double and a name (EX: 78.9 some-name).

In my main I have the following:

Transaction_List transactions {};   
Date d1 {1,29,2018,12,34,56};
Transaction t1 {9.75, "some name"};
if(transactions.add_transaction(d1,t1))
    cout << "transaction added" << endl;

In Transaction_List.h I have:

public:
bool add_transaction(Date d, Transaction t);
private:
map<Date, Transaction> transactions;

and lastly, in Transaction_List.cpp :

bool Transaction_List::add_transaction(Date d, Transaction t){
    cout << t.get_name() << endl;
    return transactions.insert(make_pair(d,t)).second;
}

In my main.cpp when I execute:

cout << t1.get_name(); 

(which I do have implemented properly, didn't include it because this post will be long enough as is), the correct name is output to the terminal. Similar can be said about any dates I create.

My problem is that when I try to execute:

cout << t.get_name() << endl; 

in Transaction_List.cpp , it spits out garbage. Essentially any Date or Transaction I create is turned into garbage values upon being sent to Transaction_List.cpp .

If the previous is not sufficent information, This link is to a google drive folder of all the files

This is for a school assignment. What I'm supposed to have at the end of the day is a list of transactions associated with a particular date that I can search through, add too, and subtract from by date or by transaction.

I followed your link and investigated the code.

As @super points out, your copy constructor isn't working properly. For your Transaction.cpp :

#include "Transaction.h"

...

Transaction::Transaction(double p, string n) {
    price = p;
    name = n;
}

// This is your implementation of the copy constructor
Transaction::Transaction(const Transaction& orig) {
}

Apparently, you are leaving the copy constructor of class Transaction empty. It seems that Date 's is also empty.

As a result, while executing this chunk of codes:

if(transactions.add_transaction(d1,t1))
    cout << "transaction added" << endl;

since you are passing objects of Transaction and Date by value, copy constructor of these two classes are called. However, because your copy constructors are empty, you actually add in a transaction object with two fields price and name uninitialized. That's why you are seeing strange values from the output.

To fix it, you can simply delete your copy constructor for Transaction and Date

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