【发布时间】:2015-11-17 01:00:19
【问题描述】:
我正在尝试通过使用带有 qt 的设计模式中的示例来了解虚拟函数的行为
这里我有一个头文件,其中定义了 2 个类:
#ifndef ABCLASSES_H
#define ABCLASSES_H
#include <QTextStream>
class A
{
public:
virtual ~A()
{
}
virtual void foo(QTextStream& out);
virtual void bar(QTextStream& out);
};
class B: public A
{
public:
void foo(QTextStream& out);
void bar(QTextStream& out);
};
#endif // ABCLASSES_H
这是这些类的源文件
#include "abclasses.h"
void A::foo(QTextStream& out)
{
out << "A's foo" << endl;
bar(out);
}
void A::bar(QTextStream& out)
{
out << "A's bar" << endl;
}
void B::foo(QTextStream& out)
{
out << "B's foo" << endl;
A::bar(out);
}
void B::bar(QTextStream& out)
{
out << "B's bar" << endl;
}
问题是我无法从这些定义中创建或使用任何类。我得到的错误是
main.obj:-1: error: LNK2001: unresolved external symbol "public: virtual void __cdecl A::foo(class QTextStream &)" (?foo@A@@UEAAXAEAVQTextStream@@@Z)
main.obj:-1: error: LNK2001: unresolved external symbol "public: virtual void __cdecl A::bar(class QTextStream &)" (?bar@A@@UEAAXAEAVQTextStream@@@Z)
因为我对虚函数了解不多。我认为可能需要重新声明 B 类中的函数,但这也无济于事,并在我的日志中增加了 2 个错误。
main.obj:-1: error: LNK2001: unresolved external symbol "public: virtual void __cdecl B::foo(class QTextStream &)" (?foo@B@@UEAAXAEAVQTextStream@@@Z)
main.obj:-1: error: LNK2001: unresolved external symbol "public: virtual void __cdecl B::bar(class QTextStream &)" (?bar@B@@UEAAXAEAVQTextStream@@@Z)
本书示例只是在声明函数后(在同一个文件中)实现了函数,这似乎可行。我想知道为什么我的不起作用以及是否有解决方法
编辑: 项目文件使用以下设置:
#-------------------------------------------------
#
# Project created by QtCreator 2015-08-23T11:53:16
#
#-------------------------------------------------
QT += core
QT -= gui
TARGET = untitled1
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
SOURCES += main.cpp \
student.cpp \
abclasses.cpp
HEADERS += \
student.h \
abclasses.h
我不得不说,在构建、链接东西方面我没有太多想法,但我现在不应该将它们集中在一个小项目上。由于 abclases.cpp 在来源中,我认为它用于构建过程。
student.h 和 .cpp 与我在同一个项目中的另一个试用有关。它们现在没有被积极使用,下面是 main.cpp
#include <QCoreApplication>
#include <QTextStream>
//#include "student.h"
#include "abclasses.h"
//void finish(Student& student)
//{
// QTextStream cout(stdout);
// cout << "The following " << student.getClassName()
// << "has applied for graduation" << endl
// << student.toString() << endl;
//}
int main() {
QTextStream cout(stdout);
B bobj;
// A *aptr = &bobj;
// aptr->foo(cout);
// cout << "-------------" << endl;
// A aobj = *aptr;
// aobj.foo(cout);
// cout << "-------------" << endl;
// aobj = bobj;
// aobj.foo(cout);
// cout << "-------------"<< endl;
// bobj.foo(cout);
}
编辑 2:更新过时的错误消息,更新 abclasses.h
【问题讨论】:
-
你必须在
B类中声明被覆盖的函数。 -
至于您的问题,您实际上是在构建 包含函数定义的源文件吗?我怀疑你也打算在
Bpublic中创建这些功能。 -
我尝试在“public:”下的 B 类中声明它们,但正如我所说,它只是向我介绍了另外 2 个错误。由于我无法真正有效地使用此编辑器,因此我正在更新有关“构建”部分的问题。
-
听起来 abclasses.cpp 没有被编译和/或链接。你能发布'make'的输出吗?
-
尽管我在 qt 中重建项目之前反复使用 clean,但它给出了相同的错误。但是在手动删除项目文件夹后,错误就消失了。感谢您为我指明正确的方向。 现在我要搜索关于 qt clean 方法的错误报告。
标签: c++ qt external virtual symbols