这是网易云课堂C++学习的第五单元作业,玩了一周,错过作业提交时间,没有测试,但做的时候还是发现不少问题
#include<string>
#include<cstdlib>
#include<iostream>
#include<string>
using std::string;
class Screen
{
public:
Screen(int width,int height):enter("enter screen"),leave("leave screen")//使用参数列表初始化类中其他类的对象
{
setWidth(width);
setHeight(height);
std::cout<<enter<<std::endl;
};
void setWidth(int width)
{
Screen::width=width;
exitWhenInvalidScreen(width, 600);
}
void setHeight(int height)
{
Screen::height=height;
exitWhenInvalidScreen(600, height);
}
int getWidth()
{
return width;
}
int getHeight()
{
return height;
}
static Screen* getInstance(int width=640, int height=480)
{
if(instance==0)
{
instance=new Screen(width,height);
}
return instance;
}
private:
int width;
int height;
string enter;
string leave;
static Screen* instance;
void exitWhenInvalidScreen(int width,int height)
{
while(width<0||width>1000||height<0||height>1000)
{
std::cout<<"invalid screen size";
exit(0);
}
}
};
Screen* Screen::instance=0;
int main()
{
int width, height;
Screen *screen1, *screen2;
std::cin >> width >> height;
screen1 = Screen::getInstance(width, height);
screen2 = Screen::getInstance();
std::cout << screen1->getWidth() << ' ' << screen1->getHeight() << std::endl;
std::cout << screen2->getWidth() << ' ' << screen2->getHeight();
#ifdef DEBUG
std::cin.get();
#endif
return 0;
}