有人可以告诉,在这段代码中如何声明构造函数,以便在实例化对象时,使用传递的值初始化高度,而宽度始终是默认值(在下面的情况下为 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
有人可以告诉我如何声明构造函数以使输出如下所示(我想声明只有一个参数的对象)?
w = 1 h = 1
w = 1 h = 2
w = 1 h = 4
w = 1 h = 5