我正在用QVariant发现自定义类型,并试图在我的项目中实现它。问题是,当我认为它会使用复制构造函数时,它似乎创建了一个带有默认构造函数的对象.
也许有些事我不明白..。
这是我的定制课程:
Parameter.h
#ifndef PARAMETER_H
#define PARAMETER_H
#include <QDebug>
#include <QMetaType>
#include "variable.h"
#include <QAbstractTableModel>
class Parameter : public Variable, public QAbstractTableModel
{
public:
Parameter();
Parameter(QString name, int min, int max, int val, QObject *parent);
Parameter(const Parameter &source);
private:
int m_value;
};
Q_DECLARE_METATYPE(Parameter)
#endif // PARAMETER_HParameter.cpp
包括参数.h
Parameter::Parameter() : Variable()
{
qDebug()<<"Default constructor";
m_value = 0;
setName("Test");
}
Parameter::Parameter(QString name, int min, int max, int val, QObject *parent)
: Variable(name, min, max), QAbstractTableModel(parent)
{
qDebug()<<"constructor";
m_value = val;
}
Parameter::Parameter(const Parameter &source)
: Variable(source.getName(), source.getMin(), source.getMax()),
QAbstractTableModel(),
m_value(source.m_value)
{
qDebug()<<"copy constructor";
}我在类MainWindow中创建了一个参数实例。以下代码是该类构造函数的摘录:
Parameter *param = new Parameter("Param",0,100,10, this);
QVariant v = QVariant::fromValue(param);
Parameter op = v.value<Parameter>();
qDebug()<< op.getName();此代码的输出是:
constructor
Default constructor
Default constructor
"Test"我想了解为什么默认构造函数会被调用两次。以及我应该做的事情,以便它调用复制构造函数(以获得我创建的对象,其名称为“Param”)。
非常感谢你的回答:)
发布于 2018-05-09 12:25:49
您可以将指针存储在QVariant中而不是值中。但想要找回价值。
如果无法转换值,则将返回默认构造的值。
因此,v.value<Parameter>();返回默认构造的对象,因为Parameter*不能转换为Parameter。
https://stackoverflow.com/questions/50253277
复制相似问题