[英]How to use an initialization list to call a constructor?
Hello I am rather new to C++ and looking to call the Rectangle
constructor from the Square
constructor using an initialization list, in order to assign values to sideA
and sideB
of the square.您好,我是 C++ 的新手,希望使用初始化列表从
Square
构造函数调用Rectangle
构造函数,以便为正方形的sideA
和sideB
赋值。 Any advice will be appreciated.任何建议将被认真考虑。
class Rectangle
{
public:
Rectangle (int a, int b);
// ...
public:
int sideA;
int sideB;
};
Rectangle::Rectangle (int a, int b) {
sideA = a;
sideB = b;
if (a < 1)
sideA = 1;
if (b < 1)
sideB = 1;
}
class Square: public Rectangle
{
public:
Square(int); //constructor
void setSideA(int);
void setSideB(int);
};
Square::Square (int a) {
sideA = a;
sideB = a;
}
void Square::setSideA(int a) {
sideA = a;
sideB = a;
if (a < 1)
sideA = 1;
sideB = 1;
}
void Square::setSideB(int b) {
sideA = b;
sideB = b;
if (b < 1)
sideA = 1;
sideB = 1;
}
You can call the base class ( Rectangle
) constructor in the initializer list part of the derived class ( Square
) constructor, thus initializing the "base component" of the derived class in the same way as you can initialize data members (as shown in the initializer list for the Rectangle
constructor in the below code):您可以在派生的 class (
Square
) 构造函数的初始化列表部分调用基 class ( Rectangle
) 构造函数,从而以与初始化数据成员相同的方式初始化派生的 class 的“基本组件”(如以下代码中Rectangle
构造函数的初始化列表):
class Rectangle {
private:
int sideA, sideB;
public:
Rectangle(int a, int b) : sideA{ std::max(1,a) }, sideB{ std::max(1,b) } {} // Initialize data
//...
};
class Square : public Rectangle {
public:
Square(int s) : Rectangle{ s, s } {} // 'Initializer list' calls base class c'tor
//...
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.