[英]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. 我遇到的情况是我想创建一个新类,然后在另一个创建的类(C ++)中使用它,但不使用不同的头文件或源文件:两个类应以一种或另一种方式放置在同一位置。 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: 但是,让我们假设我只想在那里拥有该指针,而无需调用ChildClass的方法,因此我应该只能声明ChildClass,然后在定义MainClass的同一.cpp文件中对其进行定义:
//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):
但是,特别是尝试使用我的一个类(基于Qwt的QwtPlotPicker类)来执行此操作时,出现了一些编译错误(在最后一个版本中):
error: undefined reference to `vtable for Picker'
The error points out where in the following code (in the .cpp): 该错误指出以下代码(在.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?
我会得到什么“对“ vtable”的未定义引用”的问题?
Thanks for any help, 谢谢你的帮助,
Momergil Momergil
This is a problem I have had forever when using QT. 这是我使用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).
在运行qmake之前,任何包含Q_OBJECT宏的类都必须在HEADERS中列出(据我所知)。 This may even mean putting the .cpp file in the HEADERS section.
这甚至可能意味着将.cpp文件放在HEADERS部分中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.