本題來(lái)自中國(guó)mooc《C++程序設(shè)計(jì)(面向?qū)ο筮M(jìn)階)》課程作業(yè)撑毛。
1.考慮創(chuàng)建一個(gè)繪圖程序夯尽。需要有一個(gè)類Screen用來(lái)表示繪圖時(shí)所用的屏幕
這個(gè)屏幕有一些基本屬性禾唁,比如寬和高参淫;有一些基本操作残拐,比如獲取屏幕的寬和高(10分)
題目?jī)?nèi)容:
Screen類有兩個(gè)私有的int型數(shù)據(jù)成員,分別代表屏幕的寬和高
Screen類的有參構(gòu)造函數(shù):
1)有兩個(gè)整型參數(shù)瑞侮,分別是屏幕的寬和高(以像素為單位)
2)構(gòu)造函數(shù)將屏幕的寬和高存儲(chǔ)在類的私有數(shù)據(jù)域中Screen類的無(wú)參構(gòu)造函數(shù)
1)Screen類的默認(rèn)構(gòu)造函數(shù)將屏幕寬和高分別設(shè)置為640和480的圆,也可以使用C++11的就地初始化設(shè)置屏幕寬和高
2)構(gòu)造函數(shù)將屏幕的寬和高存儲(chǔ)在類的私有數(shù)據(jù)域中Screen類的所有構(gòu)造函數(shù)均應(yīng)輸出字符串“screen”并換行,代碼中的換行需使用 cout::endl
為私有數(shù)據(jù)成員提供getter和setter函數(shù)半火,如有必要越妈,則增加其他數(shù)據(jù)成員及函數(shù)成員。函數(shù)原型如下
int getWidth();
int getHeight();
int setWidth(int width); //return width
int setHeight(int height); //return height代碼所用的主函數(shù)如下(不得做更改):
int main() {
int width, height;
std::cin >> width >> height;
Screen screen1 (width, height);
Screen screen2;
screen2.setWidth(800);
screen2.setHeight(600);
// 下面兩行代碼所輸出的寬和高之間有一個(gè)空格字符分隔
std::cout << screen1.getWidth() << ' ' << screen1.getHeight() << std::endl;
std::cout << screen2.getWidth() << ' ' << screen2.getHeight();
ifdef DEBUG
std::cin.get();
endif
return 0;
}
輸入格式:
兩個(gè)由空格分隔的整數(shù)钮糖,代表屏幕的寬和高
輸出格式:
兩次調(diào)用構(gòu)造函數(shù)所輸出字符串梅掠,字符串后換行
兩個(gè)不同屏幕對(duì)象的寬和高,由空格分隔店归,第一個(gè)屏幕對(duì)象的寬和高輸出后換行
輸入樣例:
320 240
輸出樣例:
screen
screen
320 240
800 600
注意 :上述輸出一共4行阎抒,最后一行后面 沒有 換行
答案如下:
#include <iostream>
class Screen {
private:
int width, height;
public:
Screen(int width_=640,int height=480);\\設(shè)置初始值
void setWidth(int width_);
void setHeight(int height_);
int getWidth();
int getHeight();
~Screen();
};
Screen::Screen(int width_, int height_)
{
width = width_;
height = height_;
std::cout << "screen" << std::endl;
}
Screen::~Screen()
{
}
void Screen::setHeight(int height_)
{
height = height_;
}
void Screen::setWidth(int Width_)
{
width = Width_;
}
int Screen::getHeight()
{
return height;
}
int Screen::getWidth()
{
return width;
}
int main() {
int width, height;
std::cin >> width >> height;
Screen screen1(width, height);
Screen screen2;
screen2.setWidth(800);
screen2.setHeight(600);
// 下面兩行代碼所輸出的寬和高之間有一個(gè)空格字符分隔
std::cout << screen1.getWidth() << ' ' << screen1.getHeight() << std::endl;
std::cout << screen2.getWidth() << ' ' << screen2.getHeight();
#ifdef DEBUG
std::cin.get();
#endif
return 0;
}