0

我有一组自定义按钮:

Button buttons[5]

现在我想交换这个数组的两个元素,例如buttons[1] 和buttons[2]。我该怎么做呢?只是说明以下内容,不起作用:

Button help = buttons[1];
buttons[1] = buttons[2];
buttons[2] = help;

有人可以帮我吗?

我已经使用指针数组解决了:

Button *pntArray[5];
Button *help;
pntArray[0]=&buttons[0];
pntArray[1]=&buttons[1];

help=pntArray[0];
pntArray[0]=pntArray[1];
pntArray[1]=help;
4

1 回答 1

1

QObject基类不允许赋值运算符或复制构造函数。除非您手动创建了这些(这通常是不明智的),否则请在堆上声明您的实例并使用数组中的指针。

//  Instantiate the buttons however you like, if you were just creating them
//  on the stack before, a default initialisation should suffice.  Though
//  normally in Qt you would at least pass the 'owning' widget as the parent
//  so you don't need to worry about deleting the buttons.
QVector<Button*> buttons(5);
for ( Button* button : buttons ) {  // C++11 only!
    button = new Button();
}

//  Then whenever you need to swap two entries:
std::swap( buttons[1], buttons[2] );
于 2012-07-10T12:37:15.153 回答