简体   繁体   English

QT <<过载不起作用QT5.3

[英]QT << overload not working QT5.3

I`m trying to overload the << operator for a client object: 我正在尝试为客户端对象重载<<操作符:

void Login::saveClient(Client *client)
{
    this->file = new QFile(CLIENTS_FILE);
    this->file->open(QIODevice::Append | QIODevice::Text);
    QTextStream out(this->file);
    out << client;
}

In my Client.h I have: 在我的Client.h中,我有:

class Client : public QObject
{
    Q_OBJECT

public:
    Client(QString username);

    friend QDataStream & operator <<(QDataStream &s, Client *c);

    QString getUsername();
}

In my Client.cpp: 在我的Client.cpp中:

Client::Client(QString username)
{
    this->username = username;
}

QDataStream & operator <<(QDataStream &s, Client *c)
{
    s << c->getUsername();
    return s;
}

QString Client::getUsername()
{
    return this->getUsername();
}

But in the file i get the pointer`s adress like: 但是在文件中,我得到了指针的地址,例如:

0x135551c7c0 0x135551c7c0

0x13534aa480 0x13534aa480

Can anyone help me with this? 谁能帮我这个?

With the help of moosingin3space (thanks very much) and some adaptation I managed to make this work. 在moosingin3space的帮助下(非常感谢)和一些适应,我设法完成了这项工作。 I Had to change the QDataStream to QTextStream. 我不得不将QDataStream更改为QTextStream。

Thank you all ! 谢谢你们 !

When you define the << operator, it should be defined like so: 当定义<<操作符时,应按如下方式定义:

QDataStream& operator<<(QDataStream& s, const Client& c)

The streaming operators in C++ are designed to work on references, not pointers. C ++中的流运算符旨在处理引用,而不是指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM