MrElmar
MrElmar

Reputation: 288

How to overload operator <<

I try to overload operator << in Qt.

class MyCryptographicHash : public QCryptographicHash
{
public:
    MyCryptographicHash(Algorithm method);

    void addData(const QString &data );

    friend MyCryptographicHash& operator<< (MyCryptographicHash &obj, const QString &value);

private:
    QByteArray _data;
};

MyCryptographicHash& operator<<(MyCryptographicHash &obj, const QString &value) {
    obj.addData(value);
    return obj;
}


    MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    MyCryptographicHash *hash1 = new MyCryptographicHash(QCryptographicHash::Sha1);
    MyCryptographicHash *hash2 = new MyCryptographicHash(QCryptographicHash::Sha1);
    hash1->addData("abc1234");
    QString a;
    a = "qweer321";
    hash2<<a;
    qDebug() << "HASH1: " << hash1->result();
    qDebug() << "HASH2: " << hash2->result();
}

But I get error:

no match for 'operator<<' in 'hash2 << a'

I tried to declare the operator as a member of the class, but also get an error.

error: 'MyCryptographicHash& MyCryptographicHash::operator<<(MyCryptographicHash&, const QString&)' must take exactly one argument

What am I doing wrong?

Upvotes: 1

Views: 513

Answers (1)

john
john

Reputation: 87957

Your code should be

*hash2 << a;

hash2 is a pointer, not an object.

However in the code you posted there is no obvious reason why hash2 is a pointer. So you could just write

{
    MyCryptographicHash hash1(QCryptographicHash::Sha1);
    MyCryptographicHash hash2(QCryptographicHash::Sha1);
    hash1.addData("abc1234");
    QString a;
    a = "qweer321";
    hash2 << a;
    qDebug() << "HASH1: " << hash1.result();
    qDebug() << "HASH2: " << hash2.result();
}

which would also have the advantage of not leaking memory.

But maybe there's more to this than the code you posted.

Upvotes: 5

Related Questions