构造函数中的成员初始化
Member initialization in constructors
有人可以告诉,在此代码中如何声明构造函数,以便在实例化对象时,使用传递的值初始化高度,而宽度始终为默认值(在下面的示例中为 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
相关文章:
- 为什么在C++中首先初始化成员类
- 是否可以防止省略聚合初始化成员?
- 正在复制具有未初始化成员的结构
- 使用大括号或括号初始化成员变量
- C++结构:强制初始化成员?
- C++中未初始化成员布尔变量的默认值是多少?
- 使用默认值初始化成员引用
- 在构造函数中初始化成员时,是否应该在成员上使用 std::move?
- C++使用 { } 初始化成员变量
- 如何根据构造函数参数使用超类类型初始化成员变量?
- OpenGL C++:VBO 的结构包装器不会初始化成员
- 有没有办法在Brace中初始化成员
- 从现有 istream 或类本身创建的 istream 初始化成员 istream
- 从其后声明的另一个成员数据初始化成员数据是否为未定义行为
- 通常应用方法,使用带有构造函数委托的 SFINAE 通过类模板的构造函数初始化成员
- 如何在嵌套类中初始化成员?C
- 是否可以在构造函数主体中初始化成员变量,而不是初始值设定项列表
- 编译器错误,因为构造函数必须显式初始化成员
- 如何使用成员函数初始化成员函数指针
- C 如何使用隐藏的默认构造函数初始化成员