簡體   English   中英

將派生類中的對象插入到該對象的另一個實例中(使用vector.insert函數)C ++

[英]Inserting an object from a derived class into another instance of said object (using the vector.insert function) C++

我目前正在通過具有Road類的代碼進行工作。 它具有車道向量,並包括車道類。 車道類別具有車輛向量,每輛車都有其派生類別(汽車,摩托車,貨車)。 我希望車輛能夠安全地評估它是否可以移動到另一個車道,即插入到另一個車道的車輛矢量中(汽車需要一定的安全距離,因此我已經實現了如何知道車輛是否暢通無阻切換車道)。

void Road::Simulate(double time)
{

for (unsigned int iLane = 0; iLane < getNLanes()-1; iLane++)
{
    for (unsigned int iV = 0; iV < getCurrentLane(iLane)->getNVehiclesinLane(); iV++)
    {
        std::cout<< " AllowedOvertake TEST "<<   getCurrentLane(iLane+1)->allowedOvertake(getCurrentLane(iLane)->getCurrentVehicle(iV)->getPosition(), getCurrentLane(iLane)->getCurrentVehicle(iV)->getMinDistance())<<std::endl;
        getCurrentLane(iLane+1)->setCanOvertake(allowedOvertake(getCurrentLane(iLane)->getCurrentVehicle(iV)->getPosition(), getCurrentLane(iLane)->getCurrentVehicle(iV)->getMinDistance()));

        if (getCurrentLane(iLane+1)->getCanOvertake() == true)
        {
            getCurrentLane(iLane+1)->insertVehicle(getCurrentLane(iLane)->getCurrentVehicle(iV), 0);
            delete getCurrentLane(iLane)->getCurrentVehicle(iV);
        }

    }
}
for (unsigned int iLane = 0; iLane < getNLanes(); iLane++)
{
    getCurrentLane(iLane)->Simulate(time);

}}

我繞過了所有當前車道,但最后一條車道除外,因為該車道中的任何車輛都無法超車。 在遍歷每個車道中包含的車輛之后,我有一個函數返回一個布爾值,該布爾值確認是否可以執行超車場景。 這是在allowedOvertake() 如果返回true,則實現一個插入函數。

我的問題是:如何使這種意識形態起作用,以及具有這些setCanOvertake()getCanOvertake()函數是否明智。

一種可能的解決方案是將一輛新車推回原先的車道,但要有適當的位置,速度等。但是,我不確定如何確保所輸入的車輛具有相同的類型(汽車,貨車... )。

當前,如果我排除了insertVehicle()函數,則不會出現任何構建錯誤,並且使用QPainter繪制了車輛運動。 但是,使用insertVehicle()函數,我沒有得到任何構建錯誤,但是一旦運行項目,我確實會崩潰。

任何幫助將不勝感激,對於任何編碼錯誤,我深表歉意(我是一位敏銳的,但經驗不足的C ++用戶)。

供參考,我對上述函數的定義如下

bool Lane::allowedOvertake(double pos, double mindist)
{
    for (unsigned int iV = 0; iV < getNVehiclesinLane() - 1; iV++)
    {
        if ((fVehicles[iV]->getPosition() > pos - mindist)// If inside rear safety distance.
            || fVehicles[iV]->getPosition() < pos + mindist)// If inside front safety distance.
       {}//continue
    else {return false;}
    }
return true;
}

//IN Lane.h
bool getCanOvertake() const{return FREE_LANE_OVERTAKE;}
//IN Lane.h
void setCanOvertake(bool overtake = true){FREE_LANE_OVERTAKE = overtake;}

抱歉,給我的印象是我引用了insertVehicle()函數定義。

void Lane::insertVehicle(Vehicle*v, int ielement) {

    Vehicle* vins = new Vehicle(v->getPosition(), v->getVelocity(), v->getAcceleration());

    for (unsigned int iDist = 0; iDist < fVehicles.size()+1; iDist++){fVehicles.insert(fVehicles.begin() + (ielement+1), vins);}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM