我有一系列自定义按钮:
Button buttons[5]
现在我想交换这个数组的两个元素,例如按钮[1]和按钮[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;
答案 0 :(得分:1)
QObject
基类不允许赋值运算符或复制构造函数。除非您手动创建了这些(通常是unwise),否则请在堆上声明实例并使用数组中的指针。
// 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] );