指向C++中对象的指针
Pointers to objects in C++
我正试图通过一个实现简单车辆路由问题的小项目来掌握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
。
相关文章:
- 为什么指针对象没有调用默认构造函数
- 如何访问双指针对象中的方法
- 如何使用智能指针对象执行成员函数指针
- 调用带有指针对象错误的指针变量
- 如何从模板类重载创建的指针对象上的运算符?
- C++指针对象的运算符重载
- 如何初始化数组指针对象
- 如何打印出唯一指针对象向量中的值(基于范围的循环)?C++
- C++指针对象差异
- 涉及继承,指针对象的交易以及何时进行的问题
- 表达式必须在C 中具有指针对象类型
- 下标需要数组或指针类型表达式必须具有指针对象类型
- 字符指针对象和相应的字符数组元素比较
- 如何在 c++ 中克隆为弱指针对象
- 指针对象使用CPP中的指针表达式进行比较
- Visual Studio中智能指针对象的自定义视图
- 使用指针 /对象 /模板参数正确构成
- 如果我确定只有一个线程一次处理指针/对象,则C/C 仍应使用同步
- 如何将值分配给指针对象 c++
- 更改智能指针对象,然后访问它