无法在返回中转换 const 对象

Cannot convert const object in Return

本文关键字:转换 const 对象 返回      更新时间:2023-10-16

我不完全确定我在这里做错了什么。我有一个类,其中包含指向另一个类对象的常量指针。但是,我收到有关无法转换常量(类对象(的错误。我做错了什么?我的代码设置在我尝试执行的操作中不正确吗?

错误消息cannot convert 'const AppProfile' to 'AppProfile*' in return

我最初在我的头文件中有这个class AppProfile,我将其更改为#include "appprofile.h"这有助于删除另一个错误。

稍后我将调用run(),它将在我的 AppProfile 对象上执行run

头文件

#ifndef APPITEM_H
#define APPITEM_H
#include <QObject>
#include <QUrl>
#include <QDir>
#include "appprofile.h"
class AppItem : public QObject
{
Q_OBJECT
public:
explicit AppItem(QObject *parent = nullptr);
explicit AppItem(const AppProfile &profile,
QObject *parent);
/// App Profile
AppProfile *profile() const;
signals:
public slots:
void run();
private:
const AppProfile m_profile;
};
#endif // APPITEM_H

CPP 文件

#include "appitem.h"
#include "appprofile.h"
AppItem::AppItem(QObject *parent) :
QObject(parent)
{
}
AppItem::AppItem(const AppProfile &profile,
QObject *parent) :
QObject(parent),
m_profile(profile)
{
}
QString AppItem::name() const
{
return m_name;
}
void AppItem::run()
{
AppProfile *profile = profile();
profile->run();
}
AppProfile *AppItem::profile() const
{
return m_profile;
}

更新:跟进问题,重新保护给出的答案...

为了简单地解释我的意图,我正在分析一个 json 文件,其中包含用于创建父对象 AppItem 的数据。构造此项时,它会接受它构造的 AppProfile 对象。此对象仅在创建 AppItem 时创建一次。

知道了这一点,您建议我如何继续编辑与 AppProfile 相关的原始问题代码。假设这是足够的信息。我感谢您的帮助。这就是我用于创建应用程序项的代码的外观

AppProfile *profile = new AppProfile();
AppItem *appItem = new AppItem(profile);

对于初学者来说,要么你的代码中有拼写错误,要么函数定义不正确

AppProfile *AppItem::profile() const
{
return m_profile;
}

在类中,数据成员m_profile不是指针。

//...
private:
const AppProfile m_profile;
};

因此,如果数据成员的声明有效,则该函数应如下所示

const AppProfile *AppItem::profile() const
{
return &m_profile;
}

或者,如果数据成员声明应如下所示

//...
private:
const AppProfile *m_profile;
};

那么在任何情况下,该函数都应返回指向常量数据的指针。

const AppProfile *AppItem::profile() const
{
return m_profile;
}

这是错误消息隐含地说您的代码中有拼写错误

cannot convert 'const AppProfile' to 'AppProfile*' in return

而且,如果您在任何情况下都要更新拼写错误,则不得丢弃指针的限定符 const。