构造函数中的成员初始化

Member initialization in constructors

本文关键字:初始化 成员 构造函数      更新时间:2023-10-16

有人可以告诉,在此代码中如何声明构造函数,以便在实例化对象时,使用传递的值初始化高度,而宽度始终为默认值(在下面的示例中为 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

你问题中的措辞有点不清楚。听起来你想完全忽略宽度参数,只将宽度设为 2,而高度是可选的,默认为 1。如果是这种情况,那么您可以简单地这样做:

rectangle(int, int h=1) :width(2), height(h) {}

但我的读心术告诉我,这不是你想要的(主要是因为这是一件愚蠢的事情)。我有一种预感,你只是把你的问题措辞错了,你实际上想要这样的东西:

rectangle(int w, int h) :width(w), height(h) {} // handles 2 arguments
rectangle(int h=1) :width(2), height(h) {}      // handles 0 or 1 arguments

此配置允许三个呼叫签名。

  • 2 个参数,第一个转到宽度,第二个转到高度。
  • 1 个参数,变为高度,宽度变为 2
  • 0 个参数,宽度变为 2,高度变为 1