我有一个类
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/