【问题标题】:Could not convert from ‘QAction*’ to ‘QAction’无法从“QAction*”转换为“QAction”
【发布时间】:2011-11-23 14:28:13
【问题描述】:

当我尝试返回值时,我的 smtdplugin 实现文件中出现此错误。好的,所以我知道我正在创建一个指向 QAction 的指针,当我尝试返回它时,我不能这样做,因为我的方法正在等待对对象的引用。但我不知道如何行动(我是一个初学者) 如何避免这个问题? ,并成功返回该对象

#include "smtdplugin.h"

QAction SmtdPlugin::newItem() {

QAction *item = new QAction(NULL);

    return item; // here i get error
}

Q_EXPORT_PLUGIN2(smtdplugin,SmtdPlugin);

头文件:

#ifndef SMTDPLUGIN_H
#define SMTDPLUGIN_H

#include <QObject>
#include <QAction>
#include "smtdinterface.h"

class SmtdPlugin : public QObject,SmtdInterface  {

    Q_OBJECT
    Q_INTERFACES (SmtdInterface)

public :
    QAction newItem();

};

#endif // SMTDPLUGIN_H

接口类:

#ifndef SMTDINTERFACE_H
#define SMTDONINTERFACE_H

#include <QAction>

class SmtdInterface {

public:
    virtual ~SmtdInterface() {}
    SmtdInterface();
    virtual QAction newItem () = 0;

};

Q_DECLARE_INTERFACE(SmtdInterface,"com.trololo.Plugin.SmtdInterface/1.0")

#endif 

【问题讨论】:

    标签: c++ qt plugins qt4


    【解决方案1】:

    我不熟悉 qt 但错误是 -

    QAction* SmtdPlugin::newItem()   // Return type should be QAction* and not QAction
    {
    
        QAction *item = new QAction(NULL);
    
        return item;
    }
    

    item 的类型是 QAction* 而不是编译器所抱怨的 QAction。我认为您对空间感到困惑。

    QAction* item ; // QAction * item ; QAction *item ;
    

    以上三个约定的意思都是一样的。

    【讨论】:

    • 在您的情况下,您正在返回一个指向对象的指针,但成员函数的返回类型表示它返回一个对象。指向对象的指针和它自身的对象是两种不同的类型,并不相同。
    【解决方案2】:

    当您执行return item 时,您将返回一个指向QAction 的指针,但根据函数的声明,您会返回一个QAction,因此会出现错误。

    所以,你应该这样做:

    QAction* SmtdPlugin::newItem() {
    
        QAction *item = new QAction(NULL);
    
        return item;
    }
    

    【讨论】:

    • 由于答案解决了问题,我不会反对它。第一个建议将投反对票。 QAction 是 QObject,所以不能复制。你的 return 语句会尝试复制,但无法编译
    • 请删除您的第一个建议,因为它无效
    【解决方案3】:

    如果您需要在堆上创建操作,那么最好将返回值更改为 QAction*。

    【讨论】:

      【解决方案4】:

      在您的代码中,您返回一个类型为 QAction* 的项目:

      return item; // here i get error
      

      但您的函数签名要求您返回 QAction:

      QAction SmtdPlugin::newItem() {
      

      要解决冲突,请将函数签名更改为

      QAction* SmtdPlugin::newItem() {
      

      或 更改函数的概念,使其不再返回指针。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-22
        • 1970-01-01
        • 2012-09-09
        • 2017-11-06
        • 1970-01-01
        • 2012-02-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多