有没有办法把它作为常量传递

is there a way to pass this as const?

本文关键字:常量 有没有      更新时间:2023-10-16

我有一类项返回其大小的函数。我有一个运算符==,它获取类类型的2个常量参数,并返回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,我必须使其成为友元并将对象作为常量引用传递,或者有没有方法告诉size将类类型this作为常量???谢谢你的帮助。

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

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