c++ - C++中指向对象的指针

标签 c++ oop pointers

我试图通过一个实现简单车辆路径问题的小项目来掌握 C++ 指针和对象的窍门。尽管我的代码目前可以正常工作,但我无法摆脱我的方法完全错误的感觉。让我烦恼的是代码片段,例如:

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

if 条件中的指针 hell 情况是 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;
};

我是否完全偏离了轨道,我是否遗漏了什么,或者这种情况是否正常?

最佳答案

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

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

关于c++ - C++中指向对象的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9999277/

相关文章:

c++ - 为什么下面的程序可以编译?

c++ - 相互引用类产生 "incomplete type"错误

c++ - 在《Effective C++》书中的这个示例中,返回对象指针的函数的实现细节是什么?

c++ - 由于意外的模板参数类型推导而导致的无限递归

c++ - 有没有更好的方法来初始化 C++ 中分配的数组?

c# - 你知道任何基于 C# 的 "puzzles and answers"之类的书吗?文章?资源?

php - 如何访问 Controller 内的库?

c - 指向未知大小的现有二维数组的指针?

python - 如何根据指针地址获取指针内容

C++:使用平台独立打印 ASCII 心形和钻石