【问题标题】:Constructor of a children class that have an array that contains objects of another class具有包含另一个类的对象的数组的子类的构造函数
【发布时间】:2015-05-22 06:21:27
【问题描述】:

对话框.h

#include "WBasic.h"
#include "WButton.h"
#include "WData.h"

#ifndef WDIALOG_H_INCLUDED
#define WDIALOG_H_INCLUDED


class WDialog : public WBasic
{

    private:
    WButton wB;
    WData wD;


    public:
    //Constructor
    WDialog(const int& e = 0, const WButton& = WButton(0,0), const WData& = WData(0,0,0));

    ~WDialog();

};


#endif // WDIALOG_H_INCLUDED

对话框.cpp

#include <iostream>
#include "WDialog.h"


WDialog::WDialog(const int& e, const WButton& WBUTTON, const WData& WDATA) :
WBasic(e), wB(WBUTTON), wD(WDATA)
{
}

上面的代码效果很好,但是我试图让“WButton wB”成为一个向量,将其更改为“WButton wB[3];”

class WDialog : public WBasic
{

    private:
    WButton wB[3];
    WData wD;

};

但是我不知道如何处理构造函数。

【问题讨论】:

  • 然后你必须传递一个按钮数组。为什么不使用std::vectorstd::array

标签: c++ arrays inheritance constructor composition


【解决方案1】:

你可以使用矢量来解决这个问题。 我在下面写了一个小例子。

#include <iostream>
#include <vector>
using namespace std;

    class A{

    };
    class B{
        public:
            B():vec (4,A())
            {
            }
        private :
            vector<A> vec;
    };
    int main() {
        // your code goes here
        B obj();

        return 0;
    }

您可以观察我如何使用三个 A 类对象初始化向量 vec。

【讨论】:

    【解决方案2】:

    我认为如果可以(您的编译器支持 C++11)更喜欢 std::array

    #include <array>
    
    std::array<WButton, 3> wB;
    

    然后在您的构造函数中使用初始化列表:

    WBasic(e),
    wB{WButton(...), WButton(...), WButton(...)},
    wD(WDATA)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-17
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多