【问题标题】:Return value type does not match function type when returning pointer to constant getter返回指向常量 getter 的指针时,返回值类型与函数类型不匹配
【发布时间】:2015-03-04 13:37:36
【问题描述】:

所以我在 getter 中返回指针时遇到了一点问题

错误:

Return value type does not match the function type'

我的班级标题:

class MyClass
{
    private:
        CustomModule clientModule;
        bool initialized;

    public:
        MyClass();

        CustomModule* getClientModule() const;
}

类 cpp:

#include "MyClass.h"
MyClass::MyClass(){
    initialized = true;
}

CustomModule* MyClass::getClientModule() const{
    return &clientModule;
}

【问题讨论】:

  • 你知道const后面的getClientModule()是什么意思吗?
  • @Yakk 该函数可能不会改变任何值,对吧?
  • this 在方法中是一个指向const 的指针,这有点强。

标签: c++ pointers constants


【解决方案1】:

我的编译器给出了一个更有帮助的信息:

error: invalid conversion from ‘const CustomModule*’ to ‘CustomModule*’

const 成员函数中,对象(及其成员)是const;所以你不能返回 const 指针或对任何成员的引用。

你需要这些重载中的一个或两个:

CustomModule const * getClientModule() const;
CustomModule       * getClientModule();

const 对象上调用时返回const 指针,否则返回非const 指针。

【讨论】:

  • 我总是需要指针,所以从技术上讲,const 指针没用吗?还有为什么还要在函数名前面加const,和放在CustomModule前面有什么区别?
  • 如果您总是需要非常量,那么您确实只需要非常量版本。 CustomModule const 的意思与const CustomModule 完全相同;我喜欢把它放在符合一致性的东西之后,但如果你愿意,在某些情况下你可以把它放在开头。
  • 我想我至少总是需要它。这是一个指向我的 ModuleStructure 的指针,它正在循环设置它。该结构包含 DWORDS:基数和大小因此它会不断检查 dll 是否可以加载,如果可以,则设置基数和大小
【解决方案2】:

const 结尾的方法是const 方法。调用对象的const 实例或通过对对象的const 引用是合法的,并且它承诺它不会改变对象的状态,也不会允许其他人更改对象状态的权限路由(基本上不会直接或间接更改对象的状态)。

您的const 方法返回一个指向对象内某些内容的指针。在const 方法中,该子对象也是const。所以指向它的指针是指向const 实例的指针。然后将它作为非const 指针返回,编译器会报错。

这是正确的,因为如果您从const 方法返回指向非const 子对象的指针,则该方法将“充当间接更改对象状态的一种方式”。有人可以将const 引用到您的对象或const 实例,并获取指向对象内部内容的指针。然后他们可以修改对象的内部结构。

因此,简而言之,在const 函数中,成员是const,因此您的指针是指向const 的指针,但返回类型不是。因此,编译器错误。

创建一个返回指向 const 的指针的const getter,以及一个返回指向非const 的指针的非const getter。

在头文件中:

CustomModule const * getClientModule() const;
CustomModule       * getClientModule();

.cpp 文件中:

CustomModule const* MyClass::getClientModule() const {
  return &clientModule;
}
CustomModule      * MyClass::getClientModule() {
  return &clientModule;
}

你的代码应该开始工作了。

【讨论】:

  • 但我确实需要指针,所以唯一的解决方案是不要让它成为常量?因为它指向的不是 const
  • @PrivateerGerrit 在该函数中,它指向的 const,因为它是一个const 方法。为了更好地理解,你可以有一个const MyClass,实际上是const。那么其中的数据将是const,不是吗?并且拨打getClientModule() 是合法的。如果它返回一个指向非const 的指针,它将违反const 的正确性。 const 方法可能不会改变对象状态,也不是其他人做同样事情的权限方法。
猜你喜欢
  • 2014-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多