gpt4 book ai didi

c++ - 适本地提取 vector 中的对象类型,然后将其用于比较。 C++

转载 作者:搜寻专家 更新时间:2023-10-31 02:08:21 25 4
gpt4 key购买 nike

我有一个指向车辆的指针 vector ,其中包含汽车、卡车、摩托车等车辆。这些车辆具有与其关联的位置,并且使用 QT 中的 drawPoint() 跟踪和绘制这些位置。我想知道如何实现检查每个元素的对象类型的替代方法,即不使用 typeid。

for (unsigned int jV = 0; jV < fRoadDisp->getCurrentLane(iLane)->getNVehiclesinLane(); jV++)
{
//QPainter painter(this); //already done outside loop
QPen pointpenv(Qt::red);
pointpenv.setWidth(5);
QPen pointpenC(Qt::blue); // For a Car
pointpenC.setWidth(5);
QPen pointpenL(Qt::green); // For a Lorry
pointpenL.setWidth(5);
QPen pointpenM(Qt::yellow); // For a Motorcycle
pointpenM.setWidth(5);

double position = fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV)->getPosition();

if(typeid(fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV)) == typeid(Car*)){painter.setPen(pointpenC);}
else if(typeid(fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV)) == typeid(Lorry*)){painter.setPen(pointpenL);}
else if(typeid(fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV)) == typeid(Motorcycle*)){painter.setPen(pointpenM);}

painter.drawPoint(((iLane * (width()/fRoadDisp->getNLanes())) + width()/(2 * fRoadDisp->getNLanes())), position * height()/300);
}

上面的代码在指向车辆的指针 vector 中遍历了所有车辆,并为不同的车辆提供了不同颜色的笔,并且根据绘制的车辆类型,我希望激活适当的笔。

目前,任何点都显示为白色。一个可能的解决方案(有人告诉我)是使用静态公共(public)变量,但我不确定如何实现它来代替 typeid。

如有任何帮助,我们将不胜感激。

最佳答案

我喜欢 vahancho 建议的方法,但是考虑到必要的重构,我不会向场景添加枚举并直接将 penColor 属性赋予抽象 Vehicle,以避免检查它们的类型:

class Vehicle
{
public:
virtual QColor penColor() const { return Qt::red; }
};
class Car : public Vehicle
{
public:
QColor penColor() const { return Qt::blue; }
};

所以你可以这样选择合适的笔:

painter.setPen(QPen(fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV).penColor()));

不需要if,也不需要std::map

但是,如果您认为 penColor 属性并不完全属于 Vehicle,您可以使用一个单独的类来保存绘图信息:

struct DrawingInfo
{
DrawingInfo() : penColor(Qt::red), penWidth(5){}
DrawingInfo(QColor c) : penColor(c), penWidth(5){}
DrawingInfo(QColor c, int w) : penColor(c), penWidth(w){}

QColor penColor;
int penWidth;
};

并给一个 Vehicle 及其派生类一个它的实例:

class Vehicle
{
public:
DrawingInfo drawingInfo() const { return _drawingInfo; }
protected:
DrawingInfo _drawingInfo;
};
class Car : public Vehicle
{
public:
Car()
{
_drawingInfo.penColor = Qt::blue;
}
};

这一次,您可以这样选择合适的笔:

Vehicle v = fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV);
QPen pen(v.drawingInfo().penColor);
pen.setWidth(v.drawingInfo().penWidth);
painter.setPen(pen);

关于c++ - 适本地提取 vector 中的对象类型,然后将其用于比较。 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47670712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com