我正在尝试用c ++编写一个基本的gui库,我遇到了看似基本的继承问题。我在Component.h中有一个基类Component:
class Component
{
public:
virtual void add(Component &c);
virtual void remove(Component &c);
virtual void setBounds(int x, int y, int width, int height);
virtual void setLocation(int x, int y);
virtual void setSize(int width, int height);
virtual void setVisible(bool b);
};
我还在这里显示的相同标题中声明了一个子类框架
class Frame : public Component
{
private:
char* ftitle;
HWND* hwnd;
public:
Frame();
Frame(char* title);
void add(Component &c);
void remove(Component &c);
void setBounds(int x, int y, int width, int height);
void setLocation(int x, int y);
void setSize(int width, int height);
void setVisible(bool b);
void setTitle(char* title);
};
我在另一个名为Frame.cpp的文件中实现了这个类函数
#include "Component.h"
Frame::Frame()
{
Frame("");
}
Frame::Frame(char* title)
{
ftitle = title;
*hwnd = CreateWindow("static", title, WS_OVERLAPPEDWINDOW, 0, 0, 100, 100, NULL, NULL, GetModuleHandle(NULL), NULL);
}
void Frame::setVisible(bool visible)
{
if(visible)
{
ShowWindow(*hwnd, SW_SHOW);
}
else
{
ShowWindow(*hwnd, SW_HIDE);
}
}
void Frame::add(Component &c){}
void Frame::remove(Component &c){}
void Frame::setBounds(int x, int y, int width, int height){}
void Frame::setLocation(int x, int y){}
void Frame::setSize(int width, int height){}
void Frame::setTitle(char* title){}
然而,当我尝试编译和构建项目时,我得到了几个错误,如下所示
1>------ Build started: Project: GUI, Configuration: Debug Win32 ------
1> Frame.cpp
1> Generating Code...
1> Compiling...
1> Main.cpp
1> Generating Code...
1>Frame.obj : error LNK2001: unresolved external symbol "public: virtual void __thiscall Component::add(class Component &)" (?add@Component@@UAEXAAV1@@Z)
1>Frame.obj : error LNK2001: unresolved external symbol "public: virtual void __thiscall Component::remove(class Component &)" (?remove@Component@@UAEXAAV1@@Z)
1>Frame.obj : error LNK2001: unresolved external symbol "public: virtual void __thiscall Component::setBounds(int,int,int,int)" (?setBounds@Component@@UAEXHHHH@Z)
1>Frame.obj : error LNK2001: unresolved external symbol "public: virtual void __thiscall Component::setLocation(int,int)" (?setLocation@Component@@UAEXHH@Z)
1>Frame.obj : error LNK2001: unresolved external symbol "public: virtual void __thiscall Component::setSize(int,int)" (?setSize@Component@@UAEXHH@Z)
1>Frame.obj : error LNK2001: unresolved external symbol "public: virtual void __thiscall Component::setVisible(bool)" (?setVisible@Component@@UAEX_N@Z)
1>C:\Users\Owner\Documents\Visual Studio 2012\Projects\GUI\Debug\GUI.exe : fatal error LNK1120: 6 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
答案 0 :(得分:3)
链接器抱怨缺少Component
类方法的实现,因为它们不是纯虚方法。您可以通过将它们变为纯虚拟来解决此问题:
virtual void add(Component &c) = 0;
等等。
或者,提供实施。
请注意,您还应该为Component
提供虚拟析构函数。