tags:

views:

220

answers:

3

Hi, 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:

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. other then I do it now? Thank you.

+9  A: 

add_item should take a "const QString&" rather than a "QString&" as parameter.

A: 

The problem is that ui->lineEdit->text() appears to return a QString and not a 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. 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());
SoapBox
It can be passed by const-reference instead.
Joe Gauterin
@Joe, yes, and it only works around the issue, instead of solving it.
e8johan
+2  A: 

This line returns a QString by value

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&.

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:

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.

Kornel Kisielewicz
Dzięki Kornel. ;)
There is nothing we can do