指向C++中对象的指针

Pointers to objects in C++

本文关键字:指针 对象 C++ 指向      更新时间:2023-10-16

我正试图通过一个实现简单车辆路由问题的小项目来掌握C++指针和对象的窍门。尽管我的代码目前正在运行,但我无法摆脱我的方法完全错误的感觉。让我头疼的是一些代码片段,比如:

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

if条件中的指针地狱情况是get方法返回指向已创建对象的指针的结果。被调用的方法有:

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

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

我是不是完全偏离了轨道,我是错过了什么,还是这种情况很正常?

为了提高可读性,可以将* s更改为->:

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

此外,如果您不打算放弃该对象的所有权(在这种情况下,您没有),最好通过const引用返回:

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

并使用.,而不是->:

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

而不是(*p).x写入p->x