简体   繁体   中英

How to declare a new class in the header and define it in the source file without this errors?

I'm on the situation where I want to create a new class and then use it in another created class (C++), but without using different header or source files: both classes shall be in the same place, one way or another. The main class shall contain only a pointer to the "child" class.

Now I know that in many cases is perfectly possible to define a class in the header file. In fact, if one wants to not just set a pointer to that "child class", but actually use one of its methods already in the header file (eg, for inline methods), one would actually have to define it in the source file:

class ChildClass
{
    public:
        bool myFunctions() { return true; }
}

class MainClass
{
    private:
        ChildClass* poChildClass;
        inline bool getResult() { return poChildClass->myFunctions(); }
}

But let's suppose I want just to have that pointer there, without any call to my ChildClass' methods, so I should be able to only declare the ChildClass and later define it in the same .cpp file as MainClass is defined:

//in .hpp
class ChildClass;

class MainClass
{
    private:
        ChildClass* poChildClass;
}

//in .cpp
class ChildClass
{
    public:
        bool myFunctions() { return true; }
}

//etc.

In a first moment I don't know what could be there of a problem. But in trying to do so with one of my classes in particular (which is based on Qwt's QwtPlotPicker class), I get some compile errors (in this last version):

error: undefined reference to `vtable for Picker'

The error points out where in the following code (in the .cpp):

class Picker : public QwtPlotPicker
{
    Q_OBJECT
public:
    Picker( QWidget* canvas ) :
        QwtPlotPicker( canvas ) //Here lies the error the compiler says
//...

So what is the problem? What do I get this "undefined reference to 'vtable'" problem?

Thanks for any help,

Momergil

This is a problem I have had forever when using QT. Any class that has the Q_OBJECT macro in it MUST be listed in the HEADERS before running qmake (as far as I can tell). This may even mean putting the .cpp file in the HEADERS section.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM