C ++将私有变量类初始化为另一个类

时间:2014-03-02 22:28:40

标签: c++ qt

我正在尝试将我的私有变量“DressMen black”初始化为Dialog / QT类

class Dialog : public QDialog
{
    Q_OBJECT

public:

    explicit Dialog(QWidget *parent=0,DressMen b);
    ~Dialog();

    ........



public slots:
    ........



private slots:
  .............

private:

    Ui::Dialog *ui;

    ..........

    DressMen black;


    ..........

};

我的DressMen班.h是

class DressMen {
public:

    DressMen();
    ~DressMen(void);

    DressMen(std::string name);

    .................
}

DressMen.cpp是

DressMen::DressMen()
{
    //set values for default constructor
    ..................

}

DressMen::DressMen(std::string name){

    setType(name);

    if(name=="black1"){

            ......

     }

}

现在在我的Dialog :: Dialog中我希望init我的DressMen black1私有变量等于 - DressMen黑色(“black1”);

所以我写了

Dialog::Dialog(QWidget *parent,DressMen b) : QDialog(parent),ui(new Ui::Dialog),black(b("black1")) {
.....

}

但是编译错误了我

dialog.h:23: error: default argument missing for parameter 2 of 'Dialog::Dialog(QWidget*, DressMen)'
     explicit Dialog(QWidget *parent=0,DressMen b);

我不明白,因为我正在练习C ++ ......

感谢

1 个答案:

答案 0 :(得分:0)

如Brian Bi所示,您必须为DressMen指定默认值,或者必须使DressMen成为第一个参数。您可以执行以下操作:

class Dialog : public QDialog
{
    Q_OBJECT
public:
    explicit Dialog(QWidget *parent=0, DressMen b = DressMen("black1"));

    ...
};

或者你可以这样做:

// Dialog.h
class Dialog : public QDialog
{
    Q_OBJECT
public:
    explicit Dialog(QWidget *parent=0, DressMen b = DressMen());

    ...
};

// DressMen.h
class DressMen
{
public:
    DressMen(std::string name = "black1");

    ...
};

最有意义的解决方案取决于您希望DialogDressMen的使用方式。