Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing by reference [C++], [Qt]

Tags:

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:

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.

like image 347
There is nothing we can do Avatar asked Dec 18 '22 03:12

There is nothing we can do


2 Answers

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

like image 76
user231967 Avatar answered Jan 05 '23 17:01

user231967


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.

like image 20
Kornel Kisielewicz Avatar answered Jan 05 '23 18:01

Kornel Kisielewicz