无法在返回中转换 const 对象
Cannot convert const object in Return
我不完全确定我在这里做错了什么。我有一个类,其中包含指向另一个类对象的常量指针。但是,我收到有关无法转换常量(类对象(的错误。我做错了什么?我的代码设置在我尝试执行的操作中不正确吗?
错误消息: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。
- 为什么这个函数将"const char*"转换为"void* const"而不是"const void*"
- 'HMODULE LoadLibraryA(LPCSTR)':无法将参数 1 从 'const _Elem *' 转换为 'LPCSTR'
- 将函数参数"const char*"转换为"std::string_view"是
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- 启用从"vector<const T>&"到"const vector&"的隐式转换<T>
- 将 const 转换为 const char* 无效,我该如何解决?使用 gcc7 时失败
- C++ TCP 套接字 | 无法将"std::__cxx11::字符串"转换为"const
- C++ 无法从 const int* 转换为 const_iterator
- 为什么我的编译器在调用 const getter 函数时抛出"转换丢失(const)限定符"错误?
- 如何在 c++ 中将向量转换为<string>常量字符* const*?
- 无法从'const std::string [3]'转换为'std::string'
- 无法在返回中转换 const 对象
- Tensorflow Lite ARM64错误:无法转换‘const int8x8_t
- 一种体面的方式来转换const列表参考参数,然后传递到另一个函数
- Overloading STD :: Whow()无法转换const char*
- 使用工厂方法时编译器错误:无法转换"const std::p air<char* const
- 强制转换 const 指针以使用旧版 C 代码
- 使用地址解释强制转换const
- c++转换const引用传递
- c#可以强制转换const吗?