在Qt中,当尝试分配引用时,我收到use of deleted function
错误:
/home/niko/QT_snippets/QML1/users.cpp:16: error: use of deleted function 'User::User(const User&)'
User user=users_map.value("email@domain.com");
^
^
/home/niko/QT_snippets/QML1/users.h:7: In file included from ../QML1/users.h:7:0,
/home/niko/QT_snippets/QML1/users.cpp:1: from ../QML1/users.cpp:1:
/home/niko/QT_snippets/QML1/user.h:6: 'User::User(const User&)' is implicitly deleted because the default definition would be ill-formed:
class User : public QObject
^
/opt/Qt/5.7/gcc_64/include/QtCore/QObject:1: In file included from /opt/Qt/5.7/gcc_64/include/QtCore/QObject:1:0,
/home/niko/QT_snippets/QML1/users.h:4: from ../QML1/users.h:4,
/home/niko/QT_snippets/QML1/users.cpp:1: from ../QML1/users.cpp:1:
在C中,我总是使用指针,我从来没有遇到任何问题,但正如我在C ++中看到的,每个人都使用引用。
如何在Qt中通过引用分配对象?例如,在这一行中,我应该如何使user
对象成为users_map
对象中值的引用?
User user=users_map.value("email@domain.com");
或者可能是以下情况?
User user=&users_map.value("email@domain.com");
因为...上面的代码无法编译。我需要在Users
类的方法中使用它来访问users_map
变量中的数据。
Users
类声明为:
class Users : public QAbstractItemModel
{
Q_OBJECT
enum UserRoles {
EmailRole = Qt::UserRole + 1,
NameRole,
PasswordRole
};
private:
QMap<QString,User> users_map;
public:
explicit Users(QAbstractItemModel *parent = 0);
Q_INVOKABLE QModelIndex index(int row, int column,const QModelIndex &parent = QModelIndex()) const;
Q_INVOKABLE QModelIndex parent(const QModelIndex &child) const;
Q_INVOKABLE int rowCount(const QModelIndex &parent = QModelIndex()) const;
Q_INVOKABLE int columnCount(const QModelIndex &parent = QModelIndex()) const;
Q_INVOKABLE QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
QHash<int, QByteArray> roleNames() const;
signals:
public slots:
};
User
类声明如下:
class User : public QObject
{
Q_OBJECT
Q_PROPERTY(QString email READ get_email WRITE set_email NOTIFY emailChanged);
Q_PROPERTY(QString name READ get_name WRITE set_name NOTIFY nameChanged);
Q_PROPERTY(QString password READ get_password WRITE set_password NOTIFY passwordChanged);
private:
QString email;
QString name;
QString password;
public:
explicit User(QObject *parent = 0);
QString get_email();
void set_email(QString data);
QString get_name();
void set_name(QString data);
QString get_password();
void set_password(QString data);
signals:
void emailChanged();
void nameChanged();
void passwordChanged();
public slots:
};
答案 0 :(得分:3)
我在C ++中看到,每个人都使用引用。
你不应该相信你所看到的:)
QObject
有一个已删除的复制构造函数,因此事实上您的派生类User
也有一个已删除的复制构造函数,因此无法复制。这就是这个错误的意思:
use of deleted function 'User::User(const User&)'
在以下行中:
User user=&users_map.value("email@domain.com");
&
获取users_map.value("email@domain.com")
的地址,因此您基本上创建了User*
类型的(悬空)指针,指向由QMap::value
复制的元素。< / p>
您可以像这样更改代码以获取参考:
User& user=users_map["email@domain.com"];
请注意,没有QMap::value
实现返回引用,因此您必须使用QMap::operator[]
(您可能需要检查"email@domain.com"
是否确实是地图中包含的键;它将以其他方式默默添加。)
但请注意,QObject
(和派生类)旨在与指针一起使用,因此您的声明:
QMap<QString, User> users_map;
在Qt透视图中看起来像是一个糟糕的设计,你可能会遇到更多这种类型的错误。
BTW正确的拼写是Qt,而不是QT代表QuickTime;)