简体   繁体   中英

Pointers to objects in C++

I am trying to get the hang of C++ pointers and objects, through a small project implementing a simple Vehicle Routing Problem. Even though my code is currently working, I can't shake the feeling that my approach is completely wrong. What bugs me, are snippets of code such as :

std::map<const Route*, double>::iterator it = quantities.begin();
if ((*(*(it->first)).getDestination()).getDemand() > (*(*(it->first)).getDeparture()).getSupply())

The pointer hell situation in the if condition is the result of the get methods returning pointers to already created objects. The methods being called are :

const Departure* Route::getDeparture() const {
    return departure;
};

const Destination* Route::getDestination() const {
    return destination;
};

and

int Destination::getDemand() const {
    return demand;
};

int Departure::getSupply() const {
    return supply;
};

Am I completely off track here, am i missing something or is this type of situtation something normal?

代替(*p).xp->x

To increase readability you can change * s to -> :

if(it->first->getDestination()->getDemand() > it->first->getDeparture()->getSupply())

Also, if you aren't going to give up ownership of that object (and you aren't, in this case) it is better to return by const reference:

const Departure& Route::getDeparture() const {
  return *departure;
};

and use . , not -> :

if(it->first->getDestination().getDemand() > it->first->getDeparture().getSupply())

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