1

我正在制作俄罗斯方块。好吧,我的玻璃(QtGlass.h)创建了一个图形。我想在这里使用一个参数来指定图形应该采用的形状。

你能告诉我为什么参数会导致这个错误:

QtGlass.h:29:23: error: expected identifier before 'L'
QtGlass.h:29:23: error: expected ',' or '...' before 'L'

我在下面的评论中显示了发生此错误的位置。顺便说一句,如果我取消注释表示无参数变体的行,它就可以工作。

**Figure.h**
class Figure : public QObject {
    Q_OBJECT
...
public:
    Figure(char Shape);
    //Figure();
...
};

**Figure.cpp**
Figure::Figure(char Shape) {
//Figure::Figure() {   
    previous_shape = 1;
    colour = RED;
    ...
}

**QtGlass.h**
class QtGlass : public QFrame {
    Q_OBJECT
...
protected:
    Figure the_figure('L'); //QtGlass.h:29:23: error: expected identifier before 'L' QtGlass.h:29:23: error: expected ',' or '...' before 'L'
    //Figure the_figure;
...
};

稍后添加

当我使用这个时:

class QtGlass : public QFrame {
    Q_OBJECT
    QtGlass() : the_figure('L') {}


I get this:

QtGlass.cpp:164:50: error: no matching function for call to 'Figure::Figure()'
QtGlass.cpp:164:50: note: candidates are:
Figure.h:38:5: note: Figure::Figure(char)
Figure.h:38:5: note:   candidate expects 1 argument, 0 provided
Figure.h:20:7: note: Figure::Figure(const Figure&)
Figure.h:20:7: note:   candidate expects 1 argument, 0 provided

QtGlass.cpp

QtGlass::QtGlass(QWidget *parent) : QFrame(parent) {
    key_pressed = false;
    coord_x = 5;
    coord_y = 5;
    arrow_n = 0;
    highest_line = 21;
    this->initialize_glass();
    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(moveDownByTimer()));
    timer->start(1000);
}
4

2 回答 2

0

您不能使用该语法初始化成员对象。如果您的编译器支持 C++11 的统一初始化语法或成员变量的类内初始化,您可以这样做:

class QtGlass : public QFrame {
    Q_OBJECT
...
protected:
    Figure the_figure{'L'};
    // or
    Figure the_figure = 'L'; // works because Figure(char) is not explicit
...
};

否则,您需要在QtGlass' 构造函数初始化程序列表中初始化对象

class QtGlass : public QFrame {
    Q_OBJECT
...
protected:
    Figure the_figure;
...
};

// in QtGlass.cpp
QtGlass::QtGlass(QWidget *parent) 
: QFrame(parent)
, the_figure('L')
{}
于 2013-05-25T16:45:40.583 回答
0

您正在尝试Figure在其定义中创建一个QtGlass不允许的实例。您必须the_figure在以下构造函数中实例化QtGlass

class QtGlass : public QFrame {
    Q_OBJECT
    QtGlass() {
        the_figure = Figure('L');
    };
...
protected:
    Figure the_figure;
...
};
于 2013-05-25T16:51:06.013 回答