有没有办法将其作为常量传递?

is there a way to pass this as const?

我有 一个 class 项 一个 return 大小 的函数。 我有 operator == 它获得 class 类型的 2 个 const 参数和 return item1.size() 的结果==item2.size()。 size 函数是无参函数,只需要隐藏这个参数。

问题是当我尝试在 classes 的 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 reference 传递,或者有没有办法告诉 size 将 class type this 作为常量? ? 感谢您的帮助。

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

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