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 try to add an item to QMap by:

 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 get an error message:

 error: no matching function for call to 'Storage::add_item(QString, int) note: candidates are: void Storage::add_item(QString&, int) 

How can I send a QString via a link. another, then am I doing it now? Thanks.

+4
source share
3 answers

add_item should accept "const QString &" and not "QString &" as a parameter.

+10
source

This string returns a QString value

 ui->lineEdit->text(),ui->spinBox->value() 

Therefore, you cannot use it as a modifiable link. However, you can use it as an unmodifiable (constant) link by changing the add_item function to const QString& .

 void Storage::add_item(const QString& key,int value) { *my_map_[key] = value; } 

In addition, depending on the implementation of QString, it would be quite simple to pass it by value:

 void Storage::add_item(QString key,int value) { *my_map_[key] = value; } 

... note, however, that it is usually much more efficient to use const references with classes where possible.

+2
source

The problem is that ui->lineEdit->text() returns a QString , not a QString& .

You cannot pass this by reference to the add_item function, because it does not exist anywhere, it is just a temporary copy returned by this function. if you declare it on the stack and then pass it as shown below, it should work:

 QString qs = ui->lineEdit->text(); strg_->add_item(qs,ui->spinBox->value()); 
0
source

All Articles