c++ - 向下转换基本类型

标签 c++ inheritance

在 C++ 中,如果将基类对象实例化为基对象,然后向下转换为派生对象,是否为未定义行为?

当然,我会假设它绝对必须是未定义的行为,因为派生类对象可能有基类没有的成员变量。因此,如果类被实例化为基础对象,这些变量实际上不会存在,这意味着通过派生类指针访问它们将不得不导致未定义的行为。

但是,如果 Derived 类只提供额外的成员函数,但不包含任何其他成员数据怎么办?例如:

class Base
{
    public:
    int x;
};

class Derived : public Base
{
    public:
    void foo();    
};

int main()
{
    Base b;
    Derived* d = static_cast<Derived*>(&b);
    d->foo(); // <--- Is this undefined behavior?
}

这个程序会导致未定义的行为吗?

最佳答案

是的,它仍然是未定义的行为,因为你在向编译器撒谎 d 的真实类型。

参见标准 5.2.9/8:

An rvalue of type “pointer to cv1 B”, where B is a class type, can be converted to an rvalue of type “pointer to cv2 D”, where D is a class derived (clause 10) from B, if a valid standard conversion from “pointer to D” to “pointer to B” exists (4.10), cv2 is the same cvqualification as, or greater cvqualification than, cv1, and B is not a virtual base class of D. The null pointer value (4.10) is converted to the null pointer value of the destination type. If the rvalue of type “pointer to cv1 B” points to a B that is actually a subobject of an object of type D, the resulting pointer points to the enclosing object of type D. Otherwise, the result of the cast is undefined.

最后两句说,如果指针指向的B实际上不是D派生类的一部分,则强制转换是未定义行为。

关于c++ - 向下转换基本类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5967914/

相关文章:

c++ - 这个 std::function 类似于

c++ - 为什么 const std::random_device 不可能?

java - 设计模式处理具有许多成员的类(不是构建器)

ios - 无法为 Storyboard设置覆盖的库类

C++ - "Cannot declare parameter ' 匿名'为抽象类型”

c++ - 将一个 DLL 链接到另一个 DLL 的正确步骤

c++ - 继承类之间的通信

c++ - ( var > x) 和 ( x < var) 之间有什么区别吗?

c++ - 原始 unique_ptr 被销毁后,unique_ptr<T>::get() 返回的指针不是 nullptr

c# - 泛型继承如何作用于这种类型?