gpt4 book ai didi

c++ - 是否有可能我有一个类的前向声明,而不是在头文件中使它们成为引用或指针

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:25:57 25 4
gpt4 key购买 nike

// I prefer to perform forward declaration on myclass, as I do not
// wish to ship "myclass.h" to client
// However, the following code doesn't allow me to do so, as class defination
// is needed in header file.
//
// a.h
#include "myclass.h"
class a {
public:
a();
myclass me;
};

我尝试换一种方式。但是,我需要使用动态分配,而我通常会尽量避免这种情况。

// a.h
class myclass;
class a {
public:
a();
myclass& me;
};

// But I just wish to avoid new and delete, is it possible?
// a.cpp
#include "myclass.h"

a::a() : me(*(new myclass())) {
}

a::~a() {
delete *myclass;
}

是否可以在不使用任何引用或指针的情况下这样做? (或者更准确地说,不使用 new/delete)

最佳答案

没有。原因是,编译器需要知道对象的大小(即 myclass)才能知道对象的大小(即示例中的类“a”)。如果您只向前声明了 myclass,编译器就无法知道必须为“a”类分配的大小。

引用或指针缓解了这种情况 b/c 指针或引用在编译时具有定义的大小,因此编译器知道内存要求。

关于c++ - 是否有可能我有一个类的前向声明,而不是在头文件中使它们成为引用或指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2339077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com