crossplatform.ru

Здравствуйте, гость ( Вход | Регистрация )

> Свои объекты в QSet
Andrewshkovskii
  опции профиля:
сообщение 22.11.2009, 2:01
Сообщение #1


Активный участник
***

Группа: Участник
Сообщений: 351
Регистрация: 27.12.2008
Пользователь №: 467

Спасибо сказали: 18 раз(а)




Репутация:   1  


Цитата
QSet's value data type must be an assignable data type. You cannot, for example, store a QWidget as a value; instead, store a QWidget *. In addition, the type must provide operator==(), and there must also be a global qHash() function that returns a hash value for an argument of the key's type. See the QHash documentation for a list of types supported by qHash().

Цитата
The values stored in the various containers can be of any assignable data type. To qualify, a type must provide a default constructor, a copy constructor, and an assignment operator. This covers most data types you are likely to want to store in a container, including basic types such as int and double, pointer types, and Qt data types such as QString, QDate, and QTime, but it doesn't cover QObject or any QObject subclass (QWidget, QDialog, QTimer, etc.). If you attempt to instantiate a QList<QWidget>, the compiler will complain that QWidget's copy constructor and assignment operators are disabled. If you want to store these kinds of objects in a container, store them as pointers, for example as QList<QWidget *>.


Я так понимаю, что для того, что бы можно было хранить свои объекты в сетах, необходимо что бы у объекта были определены :
Оператор сравнения.
Конструктор копирования.
Конструктор по-умолчанию.
И ..самое страшное, что бы была определена глобальная функция qHash для своего типа данных?

Ну 3ое три то понятно, а вот насчет хэша?..это исходник QHash дописывать, что ли, придется?

Вот пока что есть :

Раскрывающийся текст
#ifndef CLUSTER_H
#define CLUSTER_H
#include <QSet>
#include <QPoint>
#include <QString>
#include <QStringList>

class Cluster
{
private :
int value_;
QSet<int> items_;
QPoint centerPos;
bool isPainted;
public :
Cluster();
Cluster(const Cluster & other);
Cluster(int item1 ,int item2, int nValue);
Cluster(int item1, int nValue);
void setValue(int newValue);
int value(){ return value_; }
QSet<int> &items() {return items_;}
QSet <Cluster> itemsToSet();
void setPainted(bool is);
QString toString(QStringList * lst);
void append(Cluster * nClust);
bool operator ==(const Cluster &other);
};

#endif // CLUSTER_H


и реализация :
Раскрывающийся текст

#include "cluster.h"

Cluster::Cluster()
{
}

Cluster::Cluster(const Cluster &other)
{
    items_=other.items();
    value_=other.value();
}

Cluster::Cluster(int item1 , int item2, int nValue)
{
   value_=nValue;
   items_.insert(item1);
   items_.insert(item2);
}

Cluster::Cluster(int item1 , int nValue)
{
   value_=nValue;
   items_.insert(item1);
}

bool Cluster::operator ==(const Cluster& other)
{
    return (items_==other.items() && value_==other.value());
}

void Cluster::setValue(int newValue)
{
    value_=newValue;
}

QString Cluster::toString(QStringList * lst)
  {
   QString str;
   QStringList * list = lst;
   QSetIterator <int> it (items_);
   str.append("|");
   while(it.hasNext())
       str.append(list->at(it.next())+" ");
   str.append("|");
   return str;
   }

void Cluster::append(Cluster * nClust)
{
   QSetIterator <int> it (nClust->items());
    while (it.hasNext())
        items_ << it.next();
}

void Cluster::setPainted(bool is)
{
    isPainted=is;
}

QSet <Cluster *> Cluster::itemsToSet()
{
    QSet <Cluster> retSet;
    QSetIterator <int> it(items_);
    while(it.hasNext())
        retSet.insert(Cluster(it.next(),0));
    return retSet;
}


и тысячи ошибок от QSTL, но вот основные стопы в этом :
Цитата
C:/storage/programming/workspace/clusters/../../Qt/include/QtCore/../../src/corelib/tools/qhash.h:855: error: no matching function for call to 'qHash(const Cluster&)'


Цитата
C:/storage/programming/workspace/clusters/../../Qt/include/QtCore/../../src/corelib/tools/qhash.h:855: error: no matching function for call to 'qHash(const Cluster&)
Почему-то вот для этой функции
  inline bool same_key(uint h0, const Key &key0) { return h0 == h && key0 == key; }

'


Так чтоже мне делать? писать qHash для своего объекта и что ещё?

и ещё, вопрос из-за не достаточного знания C++,
есть в этом классе такой метод :

 const QSet<int> &items() {return items_;}


Почему, когда я пытаюсь сделать вот так вот :
if (!(ribs.at(k)->items() &= ribs.at(l)->items()).empty())

ribs это QVector <Cluster *>;
то получаю
error: passing 'const QSet<int>' as 'this' argument of 'QSet<T>& QSet<T>::operator&=(const QSet<T>&) [with T = int]' discards qualifiers


Что вообще обозначает данная ошибка?
Просто мне в проверках условиях не нужно менять содержимое Set'ов объекта Cluster, а оно из-за возвращения не константной ссылки меняется.Можно конечно возвращать копию, но это расход памяти...
Заранее спасибо..

Сообщение отредактировал Andrewshkovskii - 22.11.2009, 3:04
Перейти в начало страницы
 
Быстрая цитата+Цитировать сообщение

Сообщений в этой теме


Быстрый ответОтветить в данную темуНачать новую тему
Теги
Нет тегов для показа


1 чел. читают эту тему (гостей: 1, скрытых пользователей: 0)
Пользователей: 0




RSS Текстовая версия Сейчас: 26.4.2024, 16:37