このコードで、オブジェクトがインスタンス化されたときに高さが渡された値で初期化され、幅が常にデフォルト (以下の場合は 2) になるようにコンストラクターを宣言する方法を教えてください。
class rectangle{
int width, height;
public:
// rectangle(int w = 1, int h = 1): width(w), height(h){}
rectangle(int w = 2, int h=1): width(w) {height = h;}
int getW(){return width;}
int getH(){return height;}
};
int main()
{
rectangle r1(1);
rectangle r2(2);
rectangle r3(4);
rectangle r4(5);
cout << "w = " << r1.getW() <<" h = " << r1.getH() << endl;
cout << "w = " << r2.getW() <<" h = " << r2.getH() << endl;
cout << "w = " << r3.getW() <<" h = " << r3.getH() << endl;
cout << "w = " << r4.getW() <<" h = " << r4.getH() << endl;
}
Output with above code:
w = 1 h = 1
w = 2 h = 1
w = 4 h = 1
w = 5 h = 1
出力が次のようになるようにコンストラクターを宣言する方法を誰かに教えてもらえますか (パラメーターを 1 つだけ使用してオブジェクトを宣言したい)。
w = 1 h = 1
w = 1 h = 2
w = 1 h = 4
w = 1 h = 5