PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 8, 2022

[FIXED] How to insert multiple fixed objects of a class inside another class c++

 July 08, 2022     c++, class, key-value, object     No comments   

Issue

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 :)


Solution

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}}}
    {

    }
};


Answered By - user4581301
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing