簡體   English   中英

為什么dynamic_cast是邪惡的? 在這種情況下我應該使用dynamic_cast嗎?

[英]Why is dynamic_cast evil or not ? Should I use dynamic_cast in this case?

有人說the use of dynamic_cast often means bad design and dynamic_cast can be replaced by virtual functions

  1. 為什么使用dynamic_cast認為設計不好?
  2. 假設我有函數名稱func(Animal* animal, int animalType) ,func中的實現如下:

     bool func(Animal* animal, int animalType) { ... /* Animal is the base class of Bear, Panda, Fish .... dynamic_cast animal to real animals(Bear, Panda, Fish...) according to animalType. Do some processing with this specific type of animal, using its additional information beyond base class Animal. */ } 

這種情況是否正確使用了dynamic_cast

這完全是使用dynamic_cast的錯誤位置。 你應該使用多態。 每個Animal類都應該有一個virtual函數,比如, process ,在這里你應該只調用animal->process()

class Animal {
    virtual void Process() = 0;
}

class Cat : public Animal {
    void Process() { std::cout << " I am a tiny cat"; }
}

class Bear : public Animal {
    void Process() { std::cout << "I am a big bear"; }
}

void func(Animal * animal) {
    if (animal != nullptr) { animal->Process(); }
}

其他問題。

如果animal是一只Dog怎么辦,但由於蟲蟲animal_type說它是一只Cat

有時需要static_cast ,如果可能的話,使用dynamic_cast而不是dynamic_cast 動態強制轉換具有靜態強制轉換所不具備的額外性能成本。 為此,您需要確保知道正在進入的類型,因為static_cast更不安全。

起碼, animal_type應的成員Animal

從理論上講,永遠不需要進行壓鑄。 相反,您應該調整基類以包含必要的virtual方法。

在實踐中,您會遇到第三方庫等問題。 在這種情況下,修改基類不是一個選項,因此您可能被迫使用dynamic_cast ...

回到你的例子:

class Animal {
public:
    // starts moving toward `p`,
    // throws a `Unreachable` exception if `p` cannot be reached at the moment.
    virtual void moveToward(Point const& p) = 0;
}; // class Animal

然后:

bool move(Animal& animal, Point const& p) {
    try {
        animal.moveToward(p);
        return true;
    } catch (Unreachable const& e) {
        LOG(animal.id() << " cannot reach " << p << ": " << e.what());
    }

    return false;
} // move

當您使用向下轉換時,dynamic_cast很好,因為它限制您向下轉換為無關類型。 請參考這個

暫無
暫無

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

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