Home > database >  How to insert multiple fixed objects of a class inside another class c
How to insert multiple fixed objects of a class inside another class c

Time:06-29

class Distance{
private: float km;
//some member functions like 
//rounding off
}

class Payment{

private:
        std::unordered_map<std
        ::string,Distance>
        distancesFromAtoB;
        
/*e.g distancesFromAtoB [0]=. 
{"chicagoToNewYork":Distance 
chicagoToNewYork 
(101.345)}*///does not work 
// here

//Need to be inside a function 
//for it to work

auto chicagoToNewYork (){
distancesFromAtoB [0]=
{"chicagoToNewYork":Distance 
chicagoToNewYork 
(101.345)};//will work
}
}

How does I make multiple known fixed objects inside a class from another class. More specifically for key-value pair data type. I want to do like this because they are related to each other. Also the data will never change. Should I do this in main() function? Please help I don't know what to do. Thanks :)

CodePudding user response:

As Stephen Newell says in the comment, use constructors

#include <unordered_map>
#include <string>

class Distance{
private: 
    float km;
public:
    // add constructor to set members
    Distance(float km):km{km}
    {

    }
//some member functions like 
//rounding off
};

class Payment{

private:
    // define map
    std::unordered_map<std::string,Distance> distancesFromAtoB;
public:
    // use constructor to initialize map
    Payment():
        distancesFromAtoB{{"chicagoToNewYork",{101.345}},
                          {"earth to mars", {202830000}}}
    {

    }
};
  • Related