c++ - 将前向声明的指针转换为更具体的类型

标签 c++ polymorphism

我有一个类

class Shape;
class Triangle;
class Amorpher
{
public:
    Amorpher();
    Amorpher(Shape*);
    Amorpher(Shape&);
    ~Amorpher();
    Shape* pShape;
    void GetShapeArea();
    void Shapeshift(Shape&, string);
    void Shapeshift(Shape*, string);
private:
    Triangle* triangle;
};

和实现

Amorpher::Amorpher()
{
}
Amorpher::Amorpher(Shape* shape) : pShape(shape){}
void Amorpher::GetShapeArea()
{
    cout << "shape area is: " << pShape->Area();

}

Amorpher::~Amorpher()
{
}
void Amorpher::Shapeshift(Shape* shape,string shiftTo)
{
    if (shiftTo == "triangle")
    {
        (Triangle*)shape = triangle;
    }
}

三角形继承自形状。我想在 Shapeshift 方法中尝试将传递给该方法的 Shape 转换为 Triangle。并非所有形状都是三角形,但为什么我不能明确地进行此转换?前向声明与问题有什么关系吗?

最佳答案

I was trying to change the type of Shape passed into the Shapeshift method to a pointer that matches the string parameter in the same function

安全转换是dynamic_cast:

dynamic_cast<Triangle*>(shape);

如果 shape 是一个 Triangle*,这将成功并且表达式的结果将是一个有效的指针。否则,它将是一个空指针。

不安全的转换为static_cast:

static_cast<Triangle*>(shape);

如果 shape 碰巧不是 Triangle*,这将是未定义的行为,但不管怎样(只要 shape 是非空的)。

关于c++ - 将前向声明的指针转换为更具体的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28184117/

相关文章:

c++ - 已签名/未签名函数的警告

c++ - 如何提高套接字上的安全连接

c++ - 使用 MSYS2 安装后如何运行 Glade 和 Devhelp

c++ - C++中的消息多态性

arrays - 如何获取数组元素的类型?

java - Java 中子类型参数的多态性

haskell - fromInteger 如何工作?

c++ - 程序跳过 Getline() 而不接受用户输入

java - 检查消息类型时避免 instanceof

c++ - 嵌套绑定(bind)到成员,需要一个指针,得到一个引用。做什么?