c++ - 无法在 Return 中转换 const 对象

标签 c++ constants implicit-conversion

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

错误消息:无法将“const AppProfile”转换为“AppProfile*”作为返回

我最初在我的头文件 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 相关的原始问题代码。假设这是足够的信息。感谢您的帮助。这就是我用来创建 AppItem 的代码的样子

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。

关于c++ - 无法在 Return 中转换 const 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58136919/

相关文章:

c++ - g++ 4.4 const var 段错误的取消引用更改

c++ - 在 C++ 中自然禁止包装类

C - 动态整数数组错误(代码 :Blocks/Visual Studio)

c++ - 了解复制初始化和隐式转换

c - 为什么更改指向数组名称的指针会改变结果?

c++ - 条件 if 中类成员的范围

c++ - 在将对象作为 const 引用 C++ 传递时构建对象

c++ - 在 VS2008 中编译的代码不在 VS2013 中,const 重载

python初始化单独文件中的常量

arrays - char *name[10] 和 char (*name)[10] 有什么区别?