开发者

Declare a C++ class without defining it in the current translation unit

It is possible to declare a class without defining it (forward declaration) as long as it is defined later on within the translation unit. In the case of functions, one can declare a function without defining it within the translation unit, and the linker will link it to its definition in a different translation unit. Is it possible to do the same with class declarations?

(if this is not possible, is there any use to a forwardly declared class without a definition in the current TL, or is that always an error?)

something like this, except this doesn't compile:

mymain.cpp:

class myclass; // declare without defining

myclass::myclass();
void myclass::barf();

int main() {
  myclass *m = new myclass();
  m->barf();
  return 0;
}

myclass.cpp:

#include <iostream>

class myclass { // define the implementation
public:
    my开发者_StackOverflowclass();
    void barf();
};

myclass::myclass() { } //empty constructor
void myclass::barf() {
    std::cout << "barfing\n";
}


It is possible to forward-declare a class, but only pointers and references to forward-declared classes can be used. You can't use an actual object of a forward-declared class because the compiler doesn't know enough about it; in particular it doesn't know how large the object is or what its members are. Trying to forward-declare member functions (as you have done) won't work because the syntax of the forward declaration doesn't allow you to specify whether the functions are virtual or non-virtual (or perhaps inherited from some base class).

It is not often useful to forward-declare a class in a source file, but it can be useful in a header file. In particular it's common to forward-declare a class in a library's public header file and use pointers to that type as opaque handles. The class definition remains private to the library but user code can pass around pointers to objects of that class without ever knowing what the class's implementation looks like. This works particularly well when the pointers are smart pointers.


You can, but only if you use exclusively pointers or references to that class. But you can't use code referring to that class' members (variables or methods). You can only use it to declare pointer variables to that class.

I would suggest you create a myclass.h header file with myclass' full declaration, and include that header in mymain.cpp.


You can only do that through hacks.

The declare before use rule doesn't hold within a class (see here).

Otherwise you can do that by declaring your function as a template function, whose template parameter is of myclass (in your example).

The only non-hack way is to define the class (ie. by including the header file its defined in).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜