static_cast/dynamic_cast:是否更改对象
static_cast/dynamic_cast: Does it change the object?
我对C++中的static_cast
和dynamic_cast
有一些疑问。他们是否通过保留已经设置的成员变量(不能从派生传递到基的变量除外),将指针指向的对象从类A
完全更改为类B
?
我注意到,如果我有类似的东西
struct Base
{
Base() { }
virtual ~Base() { }
virtual void Method() { cout << "Base Method"; }
};
class Derived : public Base
{
public:
virtual void Method() { cout << "Override Method"; }
};
struct Derived2 : public Derived
{
Derived2() { cout << "Derived2 constructor"; }
void Method() { cout << "Override2 Method"; }
};
int main()
{
Base *myPointer = new Derived();
static_cast<Derived2*>(myPointer)->Derived2::Method();
delete myPointer;
return 0;
}
构造函数没有被调用,但方法调用了。这怎么可能?
强制转换根本不会更改对象。它们只为您提供一个不同的指针,指向继承层次结构中的相关类类型:
Derived x;
Base * p = &x;
AnotherClass * q = dynamic_cast<AnotherClass*>(p);
// q may or may not be NULL
例如,如果我们有一个层次结构AnotherClass : Base
和Derived : AnotherClass
(并且Base
是多态的),那么上面的动态转换就会成功。
当您已经知道您有一个更派生的动态类型,但恰好只有一个指向基的指针或引用时,通常可以使用static_cast
。
(静态强制转换永远不能用于从虚拟基础进行强制转换,在这种情况下,总是需要dynamic_cast
。)
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- CMake-按正确顺序将项目与C运行时对象文件链接
- 空基优化子对象的地址
- 将对象数组的引用传递给函数
- 你能重载对象变量名本身返回的内容吗
- C++使用整数的压缩数组初始化对象
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 将对象移动到std::shared_ptr
- 代理对象的常量正确性
- 提升 ASIO 无法识别计时器对象
- 如何理解C++标准N3337中的expr.const.cast子句8
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 如何返回一个类的两个对象相加的结果
- 使用std::函数映射对象方法
- 是否需要删除包含对象的"pair"?
- 如何在自删除后将对象设置为nullptr
- 使用 Sizeof、malloc 和 cast 的 C++ 对象实例化
- 如何将对象'cast'为其超类继承的类?