【发布时间】:2017-12-02 06:34:08
【问题描述】:
为什么“交叉演员”不起作用?
以下创建此对象继承模型:
FOOD
/ \
CHEESE CAKE
在这里,我尝试将static_cast 的指针从cheese 指向cake,制作芝士蛋糕:D。我从 Apple Clang/LLVM 收到以下错误:
ERROR: Static cast from 'Cheese *' to 'Cake *', which are not related by inheritance, is not allowed
但它们是通过继承相关的:它们是兄弟姐妹。
为什么我不能将cheese 转换为cake,就像我将int 转换为float 一样?为什么我不能从继承自同一个基类的派生对象中“交叉转换”?
以下是最小、完整且可验证的示例,其中包括 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;
}
【问题讨论】:
标签: oop c++11 polymorphism dynamic-cast static-cast