[英]Passing by reference [C++], [Qt]
I wrote something like this: 我写了这样的东西:
class Storage
{
public:
Storage();
QString key() const;
int value() const;
void add_item(QString&,int);
private:
QMap<QString,int>* my_map_;
};
void Storage::add_item(QString& key,int value)//------HERE IS THE SLOT FOR ADDING
{
*my_map_[key] = value;
}
and when I'm trying to add item to QMap
by: 当我试图通过以下方式将项目添加到QMap
:
class Dialog : public QDialog
{
Q_OBJECT
public:
Dialog(QWidget* = 0);
public slots:
void add_item()
{
strg_->add_item(ui->lineEdit->text(),ui->spinBox->value());//---HERE I'M "PASSING" TWO OBJECTS: QString AND int
ui->lineEdit->clear();
}
private:
Ui::Dialog* ui;
Storage* strg_;
};
I'm getting error: 我收到错误:
error: no matching function for call to 'Storage::add_item(QString, int)
note: candidates are: void Storage::add_item(QString&, int)
How am I suppose to send QString
by ref. 我怎么想通过ref发送QString
。 other then I do it now? 其他然后我现在这样做? Thank you. 谢谢。
add_item应该使用“const QString&”而不是“QString&”作为参数。
This line returns a QString by value 该行按值返回QString
ui->lineEdit->text(),ui->spinBox->value()
Hence, you can't use it as a modifiable reference. 因此,您不能将其用作可修改的参考。 However, you can use it as a non-modifiable (const) reference, by modifying the function add_item to take const QString&
. 但是,您可以将其用作不可修改(const)引用,方法是修改add_item函数以获取const QString&
。
void Storage::add_item(const QString& key,int value)
{
*my_map_[key] = value;
}
Also, depending on the implementation of QString, it might be as effective to just pass it by value: 此外,根据QString的实现,通过值传递它可能同样有效:
void Storage::add_item(QString key,int value)
{
*my_map_[key] = value;
}
... note however, that usually with classes it's a lot more effective to use const references where possible. ...但请注意,通常使用类,在可能的情况下使用const引用会更有效。
The problem is that ui->lineEdit->text()
appears to return a QString
and not a QString&
. 问题是ui->lineEdit->text()
似乎返回QString
而不是QString&
。
You cannot pass this by reference to the add_item
function because it does not exist anywhere, it's just a temporary copy returned by that function. 您不能通过引用add_item
函数来传递它,因为它在任何地方都不存在,它只是该函数返回的临时副本。 if you declare it on the stack and then pass it like below, it should work: 如果你在堆栈上声明它,然后像下面那样传递它,它应该工作:
QString qs = ui->lineEdit->text();
strg_->add_item(qs,ui->spinBox->value());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.