「クロスキャスト」はなぜ機能しないのですか?static_castの失敗を使用している "クロスキャスト"試行。どうして?
次に、このオブジェクトの継承モデル作成:D:ここ
FOOD
/ \
CHEESE CAKE
を私はチーズケーキを作り、cheese
からcake
へのポインタをstatic_cast
を試みます。私はアップルクラン/ LLVMから、次のエラー取得しています:
ERROR: Static cast from 'Cheese *' to 'Cake *', which are not related by inheritance, is not allowed
をしかし、彼らは継承によって関連している:彼らは兄弟です。私はfloat
にint
を唱えるよう
は、なぜ私は、cake
にcheese
をキャストすることはできませんか?同じ基本クラスを継承した派生オブジェクトから「クロスキャスト」できないのはなぜですか?
エラーを強調するために、static_cast
とdynamic_cast
試行が含まれている最小限で完全で検証可能な例を次に示します。
#include <iostream>
#include <string>
class Food {
public:
Food(std::string brand):brand_(brand) {}
virtual ~Food() {};
std::string brand() { return brand_; }
virtual void cut()const { std::cout << "Food cut." << std::endl; }
void eat()const { std::cout << "Food eaten." << std::endl; }
private:
std::string brand_;
};
class Cheese : public Food {
public:
Cheese(std::string brand):Food(brand) {};
virtual void cut()const { std::cout << "Cheese cut.\n"; }
void eat()const { std::cout << "Cheese eaten.\n"; }
};
class Cake : public Food {
public:
Cake(std::string brand):Food(brand) {};
virtual void cut()const { std::cout << "Cake cut.\n"; }
void eat()const { std::cout << "Cake eaten.\n"; }
};
int main() {
Food f("tbd");
Cheese c("Cheddar");
Cake cc("Cheesecake");
Food * food_ptr;
Cheese *cheese_ptr, *cheeseCake_ptr;
Cake *cake_ptr;
food_ptr = &f;
food_ptr->cut(); //-> "Food cut."
food_ptr = &c;
food_ptr->cut(); //-> "Cheese cut." Result of virtual keyword.
cheese_ptr = dynamic_cast<Cheese*> (food_ptr);
cheese_ptr->cut(); //-> "Cheese Cut." The downcast worked
food_ptr = &cc;
cake_ptr = dynamic_cast<Cake*> (food_ptr);
cake_ptr->cut(); //-> "Cake Cut." pointer reassignment and downcast worked.
cheeseCake_ptr = dynamic_cast<Cheese*> (food_ptr);
cheeseCake_ptr->cut(); //-> "Cake cut." Again, Food* dynamically casted to Cheese*
/* ~~~ NOTE: THE FOLLOWING EXAMLES INTENTIONALLY THROW ERRORS ~~~ */
/*
Dynamic cross-cast attempt:
ERROR: Assigning to 'Cheese *' from incompatable type 'Cake *'
Dynamic cast: doensn't make sense, as the relationshiop between cheese and cake is not polymorphic
*/
cheeseCake_ptr = dynamic_cast<Cake*> (cheese_ptr);
cheeseCake_ptr->cut();
/*
Static cross-cast attempt:
ERROR: Static cast from 'Cheese *' to 'Cake *', which are not related by inheritance, is not allowed
Static cast: why doesn't this work? We know the data types.
*/
cheese_ptr = &c;
cake_ptr = &cc;
cheeseCake_ptr = static_cast<Cake*> (cheese_ptr);
std::cout << "\n\n";
return 0;
}
しかし、相続が仮想ではないので、それは2倍のカロリーです:( – Quentin
私は2つを組み合わせてチーズケーキを作りたくない、私はチーズケーキを「チーズ」の代わりに「ケーキ」オブジェクト – kmiklas