我对C++中的继承概念感到困惑,假设我们有一个名为computer的类,并从computer类公开继承了一个名为laptop的类。现在,当我们在主函数中创建一个laptop类的对象时,内存中会发生什么?请解释。
我对C++中的继承概念感到困惑,假设我们有一个名为computer的类,并从computer类公开继承了一个名为laptop的类。现在,当我们在主函数中创建一个laptop类的对象时,内存中会发生什么?请解释。
class Computer {
public:
Computer() { /* whatever */}
/* whatever */
};
class Laptop : public Computer {
public:
Laptop() { /* whatever */ }
/* whatever */
};
然后...
x = new Laptop();
编译器的实现如下:
ptr = ::operator new(sizeof(Laptop))
Computer::Computer(ptr)
Laptop::Laptop(ptr)
x = ptr
栈的等效实现留给读者作为练习。
我假设您想了解多态对象的内存布局。我将尝试通过图示来展示它。考虑:
class Base()
{
public:
virtual void foo();
virtual void bar();
void hello();
private:
int variable1;
};
class Derived : public Base
{
public:
virtual void foo();
virtual void bar();
void bye();
private:
float variable2;
};
/*
Base object layout:
[vftable pointer] (points to the 1st row in the virtual function table)
[int variable1 ] (from Base)
Derived object layout:
[vftable pointer] (points to the 2nd row in the virtual function table)
[int variable1 ] (inherited from Base)
[float variable2] (from Derived)
virtual function table layout:
[&Base::foo ] [&Base::bar ]
[&Derived::foo] [&Derived::bar]
*/
笔记本电脑类包含自身和计算机类中定义的属性。派生类包含基类。这就是为什么Stroustrup选择术语“基类”而不是“超类”来指代被继承的类。超级一词意味着被继承的类更大,但事实上相反,继承类扩展了它继承的类。编译器分配足够容纳派生类的内存块。
class Computer {
char manufacturer[20];
char type[10];
}
class Laptop : Computer {
int runningTime;
}
Laptop lap = new Laptop();
内存被分配以容纳theObject的大小。 这包括可能继承的任何原语,例如int、char等。 可能在堆/栈上。