Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/ant/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 将派生对象指定给基类对象而不进行对象切片_C++_Inheritance_Virtual Inheritance - Fatal编程技术网

C++ 将派生对象指定给基类对象而不进行对象切片

C++ 将派生对象指定给基类对象而不进行对象切片,c++,inheritance,virtual-inheritance,C++,Inheritance,Virtual Inheritance,如何在没有堆分配的情况下将派生对象分配给静态类型的base 基本上,我想知道这是否可行: Base* b = new Derived; 但是没有新的和原始的指针。您无法在不切片的情况下按值将派生的对象分配给Base变量-Base变量“不够大”,无法容纳派生的类型的对象。想象一下,你仍然需要那些sizeof(派生)字节的内存来保存一个实际的对象 但是,您可以避免堆分配 将其分配为自动变量: Derived d; Base* b = &d; static Derived d; Base*

如何在没有堆分配的情况下将派生对象分配给静态类型的base

基本上,我想知道这是否可行:

Base* b = new Derived;

但是没有新的和原始的指针。

您无法在不切片的情况下按值将
派生的
对象分配给
Base
变量-
Base
变量“不够大”,无法容纳
派生的
类型的对象。想象一下,你仍然需要那些
sizeof(派生)
字节的内存来保存一个实际的对象

但是,您可以避免堆分配

将其分配为自动变量:

Derived d;
Base* b = &d;
static Derived d;
Base* b = &d;
或作为静态变量:

Derived d;
Base* b = &d;
static Derived d;
Base* b = &d;
或作为全球:

//Somewhere in global scope
Derived d;
//...somewhere in function
Base* b = &d;
或者即使在预分配内存上(免责声明:不要使用此实际代码):

最后,可以使用引用避免原始指针,但这样在初始化后就无法更改它:

Derived d;
Base& b = d;

无论哪种方式,您都必须为
派生的
对象分配足够的空间,并且必须确保它能够存活足够长的时间,因此,在原始的
派生的
被销毁后,您无法访问
基本的
对象。

您无法通过值将
派生的
对象分配给
基本的
变量,而无需切片-
基本的
变量“不够大”,无法容纳
派生的
类型的对象。想象一下,你仍然需要那些
sizeof(派生)
字节的内存来保存一个实际的对象

但是,您可以避免堆分配

将其分配为自动变量:

Derived d;
Base* b = &d;
static Derived d;
Base* b = &d;
或作为静态变量:

Derived d;
Base* b = &d;
static Derived d;
Base* b = &d;
或作为全球:

//Somewhere in global scope
Derived d;
//...somewhere in function
Base* b = &d;
或者即使在预分配内存上(免责声明:不要使用此实际代码):

最后,可以使用引用避免原始指针,但这样在初始化后就无法更改它:

Derived d;
Base& b = d;

无论哪种方式,您都必须为
派生的
对象分配足够的空间,并且您必须确保它能够存活足够长的时间,以便在原始
派生的
被销毁后,您不会访问
基本的
对象
将起作用,尽管它确实让我想知道为什么您首先需要它
将起作用,尽管它确实让我想知道为什么您首先需要它。不要忘记对齐问题。不要忘记对齐问题。