Ash*_*iya 6 c++ virtual inheritance multiple-inheritance
问候所有,
我来自Java背景,我在多重继承方面遇到困难.
我有一个名为IView的接口,它有init()方法.我想派生一个名为PlaneViewer的新类,实现上面的接口并扩展另一个类.(QWidget的).
我的实现如下:
IViwer.h(只有头文件,没有CPP文件):
#ifndef IVIEWER_H_
#define IVIEWER_H_
class IViewer
{
public:
//IViewer();
///virtual
//~IViewer();
virtual void init()=0;
};
#endif /* IVIEWER_H_ */
Run Code Online (Sandbox Code Playgroud)
我的派生类.
PlaneViewer.h
#ifndef PLANEVIEWER_H
#define PLANEVIEWER_H
#include <QtGui/QWidget>
#include "ui_planeviewer.h"
#include "IViewer.h"
class PlaneViewer : public QWidget , public IViewer
{
Q_OBJECT
public:
PlaneViewer(QWidget *parent = 0);
~PlaneViewer();
void init(); //do I have to define here also ?
private:
Ui::PlaneViewerClass ui;
};
#endif // PLANEVIEWER_H
Run Code Online (Sandbox Code Playgroud)
PlaneViewer.cpp
#include "planeviewer.h"
PlaneViewer::PlaneViewer(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
}
PlaneViewer::~PlaneViewer()
{
}
void PlaneViewer::init(){
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:
2.我无法编译上面的代码,给出错误:
PlaneViewer] + 0x28):未定义引用`typeinfo for IViewer'colle2:ld返回1退出状态
我是否必须在CPP文件中实现IView(因为我想要的只是一个接口,而不是实现)?
考虑接口类的一个好方法是它们指定派生类必须实现的方法.
是否有必要在PlaneViewer接口中声明方法init(),因为它已经在IView中定义了?
快速回答是,你必须实现init方法,IViewer因为在基类中,方法被声明为纯虚方法.这意味着任何派生类必须提供自己的方法实现,因为没有实现基类方法.
2.我无法编译上面的代码,给出错误:
PlaneViewer] + 0x28):未定义引用`typeinfo for IViewer'colle2:ld返回1退出状态
这是从具有一个纯虚拟函数的基座有一个派生类和派生类不实现纯虚法,克++编译器错误指示(如上所述),因为它必须.
哦,还应该注意到你没有多重继承的问题,如果只涉及IViewer并且PlaneViewer涉及到问题仍然存在.
是否有必要在 PlaneViewer 接口中声明方法 init() ,因为它已经在 IView 中定义了?
您不必在 PlaneViewer 中声明 init() ,但如果您不声明,PlaneViewer 将是一个抽象类,这意味着您无法实例化它。
如果您想问是否必须有“void init();” 在 PlaneViewer 的头文件和 .cpp 文件中。答案是肯定的。
我无法遵守上面的代码,给出错误:PlaneViewer]+0x28):对“IViewer的typeinfo”的未定义引用collect2:ld返回1退出状态
我认为要么您没有构建相同的代码,要么您的编译命令不正确。
我去掉了 QT 的东西,并且能够使用 g++ 构建你的代码。
该错误意味着链接器未找到 IViewer 类。
如果我删除使“IViewer::init()”成为纯虚函数的“=0”部分,则会出现该错误。如果您在 IViewer 中取消注释构造函数和/或析构函数,也可能会收到该错误。
我是否必须在 CPP 文件中实现 IView?
不。C++ 不关心它是在 .cpp 文件还是 .h 文件中。与 Java 不同,C/C++ 预处理器首先解析所有包含内容并生成一个包含所有代码的文件。然后它将其传递给 C/C++ 编译器。如果需要,您实际上可以包含 .cpp。但这不是一个好主意。