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

Che*_*eng 4 c++

// 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;
};
Run Code Online (Sandbox Code Playgroud)

我试着以另一种方式做到这一点.但是,我需要使用动态分配,我通常会尽量避免.

// 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;
}
Run Code Online (Sandbox Code Playgroud)

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

RC.*_*RC. 8

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

引用或指针缓解了这个b/ca指针或引用在编译时具有定义的大小,因此编译器知道存储器要求.