我有这个界面:
class ISocketClient
{
public:
~ISocketClient() {}
virtual bool connectToHost(std::string const &hostname, unsigned short port) = 0;
virtual void closeClient() = 0;
virtual bool sendMessage(Message &) = 0;
virtual Message *getMessage() = 0;
};
这是我继承的类:
class TCPClient : public QObject, ISocketClient
{
Q_OBJECT
public:
TCPClient(QObject *parent = 0);
~TCPClient();
bool connectToHost(std::string const &hostname, unsigned short port);
void closeClient();
bool sendMessage(Message &);
Message *getMessage();
public slots:
void readMessage();
private:
QTcpSocket *tcpSocket;
};
但是当我编译时出现这个错误:
/home/danilo_d/Epitech-Projects/Semestre5/QtNetworkTest/TCPClient.cpp:4: error: undefined reference to `vtable for TCPClient'
当我去掉我对 QObject 的继承时,它就起作用了。
知道我该怎么做吗?
最佳答案
这可能是因为您没有在构建中包含 .moc
文件。参见 Qt Linker Error: "undefined reference to vtable"但是,对于类似的问题,如果您的构建系统未知,则想法是:
a) 你需要确保 moc
在你的 .cpp
文件上运行并且
b) 生成的 .cpp
文件包含在构建中。
具体如何完成取决于构建系统。例如,在我当前的项目中,使用 Cmake 3.x.x,这个命令就足够了:
set (CMAKE_INCLUDE_CURRENT_DIR ON)
set (CMAKE_AUTOMOC ON)
对于 GNU make
,这是一个如何完成的示例:
http://doc.qt.io/qt-4.8/moc.html#writing-make-rules-for-invoking-moc
对于 qmake
,请参见示例
Why is important to include ".moc" file at end of a Qt Source code file?
至于多重继承,如果要继承多个QObject
,那是不允许的。相反,当有一个 QObject
和多个“常规”类时,效果很好。
关于c++ - 我的类(class)如何继承接口(interface)和 QObject ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40058582/