简体   繁体   English

如何使用初始化列表调用构造函数?

[英]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构造函数,以便为正方形的sideAsideB赋值。 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.

相关问题 重构构造函数以使用初始化列表 - Refactor constructor to use initialization list 如何使用初始化列表选择要使用的构造函数? - How can I use an initialization list to select which constructor to use? 使用列表初始化调用Ambigous构造函数 - Ambigous constructor call with list-initialization 什么时候不应该在构造函数中使用初始化列表? - When should we not use initialization list in the constructor? 不能使用try / catch在构造函数初始化列表中使用统一初始化 - can't use uniform initialization in constructor initialization list with try/catch 如何从成员初始化列表中调用随机生成器的 seed_seq 构造函数? - How to call the seed_seq constructor of a random generator from a member initialization list? 具有空初始化的构造函数初始化列表 - Constructor initialization list with empty initialization 如何在构造函数的初始化列表中初始化共享指针? - How to initialize a shared pointer in the initialization list of a constructor? 我应该在初始化列表中调用基类默认构造函数吗? - Should I call the base class default constructor in the initialization list? 在构造函数初始化列表中调用非静态函数,C ++ - Call non-static function in constructor initialization list, C++
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM