在Qt 5.4中使用Namespace

Using Namespace in Qt 5.4

本文关键字:Namespace Qt      更新时间:2023-10-16

我在Qt 5.4中的GraphicsList.cpp中遇到了一个问题

#include "GraphicsList.h"
GraphicsList::GraphicsList()
{
    _DesignLayerList=new QList<WorkSystem::GraphicShape>();
}
void GraphicsList::Draw(){
    for(int i=this->_DesignLayerList->count();i>=0;--i){
        WorkSystem::GraphicShape shapeObject=(WorkSystem::GraphicShape)_DesignLayerList[i];
        //        WorkSystem::GraphicShape shapeObject=_DesignLayerList[i];
        shapeObject.Draw();
    }
}

QQQ/GraphicsList.cpp:9:错误:没有c风格强制转换的匹配转换从"QList"到"WorkSystem::GraphicShape"WorkSystem: GraphicShape shapeObject = (WorkSystem:: GraphicShape) _DesignLayerList[我];^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

我GraphicList.h

#ifndef GRAPHICSLIST_H
#define GRAPHICSLIST_H
#include "GraphicShape.h"
class GraphicsList
{
public:
    GraphicsList();
    ~GraphicsList();
    void Draw();
private:
    QList<WorkSystem::GraphicShape> *_DesignLayerList;
};
#endif // GRAPHICSLIST_H
我GraphicShap.h

#ifndef GRAPHICSHAPE_H
#define GRAPHICSHAPE_H
#include <QDebug>
#include <QPainter>
namespace WorkSystem {
class GraphicShape
{
public:
    GraphicShape();
    ~GraphicShape();
    QColor _penColor;
     virtual void Draw();
};
}

#endif // GRAPHICSHAPE_H
我GraphicShape.cpp

#include "GraphicShape.h"
#include <QDebug>
WorkSystem::GraphicShape::GraphicShape()
{
    _penColor=Qt::white;
}
void WorkSystem::GraphicShape::Draw(){
    qDebug()<<"DrawDrawDrawDraw";

}
WorkSystem::GraphicShape::~GraphicShape()
{
}

请给我一些建议。

shapeLine.h

#ifndef SHAPELINE_H
#define SHAPELINE_H
#include <QDebug>
#include "GraphicShape.h"
namespace WorkSystem {
class shapeLine : public GraphicShape
{
public:
    shapeLine();
    ~shapeLine();
protected:
    void Draw();
};
}
#endif // SHAPELINE_H

shapeLine.cppdiv…

问题似乎是指针的误用。如果您查看_DesignLayerList成员的声明:

QList<WorkSystem::GraphicShape> *_DesignLayerList;

您没有声明实际的QList实例。相反,您声明了一个指向QList的指针。因此,当您使用_DesignLayerList[i]时,您实际上并没有试图查看列表,而是使用指针算术来查找另一个QList实例,这不是您所期望的。

相反,你应该声明没有星号的成员变量,这意味着将是QList的实际实例,而不是指向QList的指针:

QList<WorkSystem::GraphicShape> _DesignLayerList;

这将按预期运行。我还建议您回顾一下对指针和值之间区别的理解,因为这是c++的基础。在现代c++中,建议尽可能避免使用原始指针,而使用智能指针、引用和值类型,因为它们通常更合适、更安全。

如果你坚持使用指针,另一种方法是通过先取消对指针的引用来执行查找,这样你就可以指向它所指向的QList实例。但是,我不建议这样做,因为它增加了开销和额外的复杂性,没有任何好处:

shapeObject = (*DesignLayerList)[i]

作为使用原始指针的常见问题的一个例子:当您创建QList实例时,您从未实际删除它,因此此代码泄漏内存。