c++ - 什么是动态类型的对象

标签 c++ pointers inheritance lvalue subobject

我认为动态类型是指使用new 动态分配的对象。在下面的例子中,你说p指向动态类型还是静态类型的对象?在标准中,它没有说动态类型是动态对象。

1.3.3 - The type of the most derived object (1.8) to which the lvalue denoted by an lvalue expression refers. [Example: if a pointer (8.3.1) p whose static type is "pointer to class B" is pointing to an object of class D, derived from B (clause 10), the dynamic type of the expression *p is "D." References (8.3.2) are treated similarly. ]

还有下面这句话是什么意思

The dynamic type of an rvalue expression is its static type

class Base {
    virtual void foo(){}
};

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

int main()
{
    Derived d;
    Base *p = &d;
}

最佳答案

What i think is that dynamic type means dynamically allocated object using new.

没有。

动态类型是对象的真实类型,可以通过指向其真实类型的基类型的引用(包括指针)访问。

也就是说,如果我们有:

class A {

};

class B : public A { };


B l;
A& k = l;

这里 k 是对类型 A 对象的引用,但所引用对象的实际类型,即它的动态类型,是 B。

这里“动态”的意思是“只在运行时知道”。

关于c++ - 什么是动态类型的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7649649/

相关文章:

c - c 程序的意外行为?

java - 我如何从两个不同的抽象类中实现特定的方法?

c++ - .(点)访问静态方法

c++ - 类型错误 : Result of expression 'dbMasterObject.updateIntoTestResult' [undefined] is not a function

c++ - C++ 中用于数组的等式和赋值运算符

c++ - 在 C++ 中,如何在再次调用函数时阻止指针变为 'overridden'?

c++ - 从音频缓冲区和视频缓冲区 C++ Windows 构造 mp4 文件

c - 如何编写循环和指针算术

java - 在 Java 的父类(super class)构造函数中调用抽象方法

c# - 没有主体的虚拟方法