Qt는 解决 오류 : 삭제 기능 和의 사용은이 컨텍스트 내에서 개인이다

파일

mainwindow.h

#include <QMainWindow>
#include <QLCDNumber>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void on_pushButton_add_clicked();

    void on_pushButton_remove_clicked();

private:
    Ui::MainWindow *ui;
    QList <QLCDNumber> *m_pList;
};

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    m_pList = new QList <QLCDNumber>;
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_add_clicked()
{
    QLCDNumber *w = new QLCDNumber();
    m_pList->append(*w);
    ui->gridLayout->addWidget(w);

}

컴파일 오류

略\QtCore\qlist.h:454: error: 'QLCDNumber::QLCDNumber(const QLCDNumber&)' is private within this context
     if (QTypeInfo<T>::isLarge || QTypeInfo<T>::isStatic) n->v = new T(t);
                                                                 ^~~~~~~~
略\QtCore\qlist.h:454: error: use of deleted function 'QLCDNumber::QLCDNumber(const QLCDNumber&)'
     if (QTypeInfo<T>::isLarge || QTypeInfo<T>::isStatic) n->v = new T(t);
                                                                 ^~~~~~~~

해결 과정

 주어지고, 우리는 두 개의 오류가 말 그대로 발견 생성자이 비공개소멸자의 사용 . 첫 번째는 개인 기능이 오류를 얻을 수있는 개인 함수를 사용하여 사용할 수없는 경우, 두 번째 문장의 의미를 이해하지 않았다입니다 쉽게 이해하는 것입니다, 다음, 추가 문의는 아래로, 파일 qlist.h은 관련 코드에 주어지고, / * 번호 - - * /는 줄 컴파일러 오류의 수를 나타냅니다

template <typename T>
Q_INLINE_TEMPLATE void QList<T>::node_construct(Node *n, const T &t)
{
   /*454--*/ if (QTypeInfo<T>::isLarge || QTypeInfo<T>::isStatic) n->v = new T(t);
   /*455--*/ else if (QTypeInfo<T>::isComplex) new (n) T(t);
#if (defined(__GNUC__) || defined(__INTEL_COMPILER) || defined(__IBMCPP__)) && !defined(__OPTIMIZE__)
    // This violates pointer aliasing rules, but it is known to be safe (and silent)
    // in unoptimized GCC builds (-fno-strict-aliasing). The other compilers which
    // set the same define are assumed to be safe.
   /*460--*/ else *reinterpret_cast<T*>(n) = t;
#else
    // This is always safe, but penaltizes unoptimized builds a lot.
    else ::memcpy(n, static_cast<const void *>(&t), sizeof(T));
#endif
}

 오류는, 상기 문서에 의해 발견

if (QTypeInfo<T>::isLarge || QTypeInfo<T>::isStatic) n->v = new T(t);

 이 트리거 문장은,이 컨텍스트 내에서 추가 질문 (QLCDNumber & CONST) QLCDNumber :: QLCDNumber 자체가 생성자를 복사 (QFrame /는 QWidget / QObject를) QLCDNumber가 QLCDNumber 부모를 포함 발견 공공 (공용) 사본하지 않은 개인입니다 생성자, QLCDNumber 클래스 안에서 발견하지만, 개인 매크로를 가지고,

private:
    Q_DISABLE_COPY(QLCDNumber)

 매크로를 계속 소급,

/*
   Some classes do not permit copies to be made of an object. These
   classes contains a private copy constructor and assignment
   operator to disable copying (the compiler gives an error message).
*/
#define Q_DISABLE_COPY(Class) \
    Class(const Class &) Q_DECL_EQ_DELETE;\
    Class &operator=(const Class &) Q_DECL_EQ_DELETE;

 오류의 원인이 나타난 알 수 위의 의견에 따라, 여기. 전화 APPEND 시간의 QList, 당신은 복사 생성자의 금지 오류를 유발 트리거합니다.
 용액 QLCDNumber 감싸 외부에 있으면서 우회하기 복사 생성자 링 간단하다. 비교적 용이 때문일 수있다 QList <QLCDNumber>에 QList <QLCDNumber *>.

근본 원인을 조회합니다

 그것이 왜 오류가 알려져 있지만 일반 클래스가 더 복사 생성자가없는 이유를 알 수 없지만 그래서 문서를 확인하기 위해 계속합니다. QObject를 내용에 다음과 같은 구절을 참조하십시오

No Copy Constructor or Assignment Operator
QObject has neither a copy constructor nor an assignment operator. This is by design. Actually, they are declared, but in a private section with the macro Q_DISABLE_COPY(). In fact, all Qt classes derived from QObject (direct or indirect) use this macro to declare their copy constructor and assignment operator to be private. The reasoning is found in the discussion on Identity vs Value on the Qt Object Model page.
The main consequence is that you should use pointers to QObject (or to your QObject subclass) where you might otherwise be tempted to use your QObject subclass as a value. For example, without a copy constructor, you can't use a subclass of QObject as the value to be stored in one of the container classes. You must store pointers. 

 단락에 말했다는 Qt는 개체 모델이 원인에서 찾을 수 있습니다 소개 우리는 QObject를 (그리고 QObject를 서브 클래스)에 대한 포인터를 사용하는 것이 좋습니다, 또는 다른 값으로 사용 QObject를 관련 개체에 시도 할 수 있습니다. 예를 들어, 물체가 QObject를 기억 된 값과 관련 될 수있는 복사 생성자 없다 포인터 용기에 저장해야한다. 이것은이 문서에서 설명하는 경우 임금 인상 문제입니다.
 그럼, Qt의 객체 모델 (객체 모델) 도입으로 설정, 일부 또는 값 (값) (내가 알고있는 한, 객체에 대한 포인터를 식별하는 것입니다, 정체성) QObject를이 로고를 사용한다에 관한 다음 문서를 발견 토론,

Qt Objects: Identity vs Value
Some of the added features listed above for the Qt Object Model, require that we think of Qt Objects as identities, not values. Values are copied or assigned; identities are cloned. Cloning means to create a new identity, not an exact copy of the old one. For example, twins have different identities. They may look identical, but they have different names, different locations, and may have completely different social networks.
Then cloning an identity is a more complex operation than copying or assigning a value. We can see what this means in the Qt Object Model.
A Qt Object...
might have a unique QObject::objectName(). If we copy a Qt Object, what name should we give the copy?
has a location in an object hierarchy. If we copy a Qt Object, where should the copy be located?
can be connected to other Qt Objects to emit signals to them or to receive signals emitted by them. If we copy a Qt Object, how should we transfer these connections to the copy?
can have new properties added to it at runtime that are not declared in the C++ class. If we copy a Qt Object, should the copy include the properties that were added to the original?
For these reasons, Qt Objects should be treated as identities, not as values. Identities are cloned, not copied or assigned, and cloning an identity is a more complex operation than copying or assigning a value. Therefore, QObject and all subclasses of QObject (direct or indirect) have their copy constructor and assignment operator disabled. 

 값의 사용 (복사) 또는 할당을 복사하면 문제가 많이 나타납니다 때 인해 Qt는 개체 모델의 특성이 즉, (=) 따라서, QObject를하고있는 QObject의 모든 하위 클래스를 사용할 수 없습니다 복사 생성자와 할당하다 운영자.

결론

 QObject를 대신 포인터 값을 사용하여 객체를 관련.

게시 60 개 원래 기사 · 원 찬양 18 ·은 20000 +를 볼

추천

출처blog.csdn.net/BadAyase/article/details/103407528