【问题标题】:is there a way to pass this as const?有没有办法将它作为 const 传递?
【发布时间】:2016-01-10 20:29:47
【问题描述】:

我有一类项目一个返回其大小的函数。 我有 operator ==,它获取类 类型的 2 个 const 参数并返回 item1.size() == item2.size () 的结果。 size 函数是非参数函数,只需要隐藏这个参数。

问题是当我尝试在类的 const 引用上使用 size 时,它​​给了我一个错误:

'function' : cannot convert 'this' pointer from 'type1' to 'type2'

The compiler could not convert the this pointer from type1to type2.

This error can be caused by invoking a non-const member function on a const object. Possible resolutions:

    Remove the const from the object declaration.

    Add const to the member function.

关于我的问题的那段代码:

bool operator==(const CardDeck& deck1, const CardDeck& deck2){
    if (deck1.size() != deck2.size()) {
        return false;
    }
    //...
}

错误:

 'unsigned int CardDeck::size(void)' : cannot convert 'this' pointer from 'const CardDeck' to 'Cardeck&'

如果我希望该 size 将对象作为 const,我必须使它成为朋友并将对象作为 const 引用传递,或者有没有办法告诉 size 将类类型作为常量? 感谢您的帮助。

【问题讨论】:

  • 你做了CardDeck::size() const吗?
  • 据我了解,将其设为 const 意味着将其参数设为 const,而这里仅此而已。写 const CardDeck::size() 只意味着返回的值(不是通过引用,而是它的副本)将是 const,这并不意味着什么,我错了吗?这就是为什么我问是否有办法告诉编译器这是方法大小的常量。
  • 您可以通过在函数声明之后但在其主体之前添加 const 关键字来创建整个函数 const。与返回类型或参数无关。

标签: c++ class constants this


【解决方案1】:

您很可能忘记将 size 成员函数限定为 const:size_t size() const { return /* compute/return size */; }

另一种选择是您确实在某处将CardDeck 拼写为Cardeck(错误消息中的拼写)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-18
    • 2015-07-08
    • 2021-12-20
    • 2019-07-30
    相关资源
    最近更新 更多