這個 C 代碼片段有什么作用?
IEntity* wLocalEntity= const_cast<IEntity*>(BaseSimSystem::getEntityRef());
if(wLocalEntity!=0){
mEntitySpeed=wLocalEntity->getSpeed();
}
我不確定它與模板創建有何關系。有人可以向我解釋這段代碼的作用嗎?謝謝你。
uj5u.com熱心網友回復:
這是代碼。
IEntity* wLocalEntity= const_cast<IEntity*>(BaseSimSystem::getEntityRef());
if(wLocalEntity!=0){
mEntitySpeed=wLocalEntity->getSpeed();
}
如果你真的被問到這個代碼,我要做的第一件事就是抱怨 if 子句。0 應該是 nullptr 如下:
if (wLocalEntity != nullptr) {
mEntitySpeed = wLocalEntity->getSpeed();
}
另外,請告訴我你知道你不應該如此緊密地壓縮你的代碼。當您將所有這些運算子推到一起而沒有空格時,錯誤就會隱藏起來。
現在,讓我們看看第 1 行:
IEntity* wLocalEntity = const_cast<IEntity*>(BaseSimSystem::getEntityRef());
顯然,wLocalEntity 是指向 IEntity 的指標。我希望你明白這一點。
這const_cast<>有點荒謬,可能是一個錯誤。我們不知道 BaseSimSystem::getEntityRef() 回傳什么,但我懷疑它回傳一個 const 指標,現在您正試圖將其分配回非常量變數。const_cast<> 正在擺脫常量性。
正確的代碼幾乎肯定是:
const IEntity * wLocalEntity = BaseSimSystem::getEntityRef();
但是,IEntity 的方法可能不是真正應該標記為 const 的方法,因此您可能必須這樣做,因為其他一些程式員沒有在他應該使用的時候應用 const。
所以const_cast<IEntity *>說“在這些括號中取回傳值,是的,我知道它們不是非常量 IEntity *,但不要警告我,因為我應該知道我在做什么。
怎么樣?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/380312.html
上一篇:依賴于模板引數的型別定義
