在声明ComponentBase为Window和ScrollBar的虚基类后, 派生类WindowScrollBar中不需要将setHeight(), setWidth()等函数覆盖
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <cstdlib>
using namespace std;
class ComponentBase
{
private:
int width;
int height;
protected:
std::string name;
public:
ComponentBase(std::string name);
void setWidth(int width);
void setHeight(int height);
void showSize();
void showName();
};
ComponentBase::ComponentBase(std::string name)
{
this->name=name;
}
void ComponentBase::setWidth(int width)
{
this->width=width;
}
void ComponentBase::setHeight(int height)
{
this->height=height;
}
void ComponentBase::showSize()
{
std::cout<<"组件"<<this->name<<"高:"<<this->height<<" 宽:"<<this->width<<std::endl;
}
void ComponentBase::showName()
{
std::cout<<"组件名:"<<this->name<<std::endl;
}
class Window:public virtual ComponentBase //声明ComponentBase为Window的虚基类
{
private:
std::string icon;
public:
Window(std::string name):ComponentBase(name)
{
std::cout<<"构造组件名为"<<this->name<<"窗体对象"<<std::endl;
}
void setIcon(std::string icon);
void showIcon();
~Window();
};
void Window::setIcon(std::string icon)
{
this->icon=icon;
}
void Window::showIcon()
{
std::cout<<"窗体图标"<<this->icon<<std::endl;
}
Window::~Window()
{
std::cout<<"清理组件名为"<<this->name<<"窗体对象"<<std::endl;
}
class ScrollBar:public virtual ComponentBase //声明ComponentBase为Window的虚基类
{
private:
std::string orientation;
public:
ScrollBar(std::string name):ComponentBase(name)
{
std::cout<<"构造组件名为"<<this->name<<"滚动条对象"<<std::endl;
};
void setorientation(std::string orientation);
void showOrientation();
~ScrollBar();
};
void ScrollBar::setorientation(std::string orientation)
{
this->orientation=orientation;
}
void ScrollBar::showOrientation()
{
std::cout<<"滚动条方向为"<<this->orientation<<std::endl;
}
ScrollBar::~ScrollBar()
{
std::cout<<"清理组件名为"<<this->name<<"滚动条对象"<<std::endl;
}
class ScrollBarWindow:public Window,public ScrollBar
{
public:
ScrollBarWindow(std::string windowName,std::string scrollBarName):Window(windowName),ScrollBar(scrollBarName),ComponentBase(windowName)
{
std::cout<<"构造名为"<<this->name<<"带有滚动条的窗体对象"<<std::endl;
}
~ScrollBarWindow()
{
std::cout<<"清理名为"<<this->name<<"带有滚动条的窗体对象"<<std::endl;
}
};
int main()
{
{
ScrollBarWindow scrollBarWindow("form1","scrollBar1");//设置窗体名和滚动条名
scrollBarWindow.setHeight(400);//设置窗体高
scrollBarWindow.setWidth(200);//设置窗体宽
scrollBarWindow.setIcon("BattleField3");//设置窗体图标
scrollBarWindow.setorientation("Vertical");//设置滚动条方向
scrollBarWindow.showName();//显示窗体名称
scrollBarWindow.showSize();//显示窗体大小
scrollBarWindow.showIcon();//显示窗体图标
scrollBarWindow.showOrientation();//显示滚动条的方向
}
system("pause");
return 0;
}