2016-01-10 123 views
1

我有一类函数返回它的大小。 我有运算符==它得到2类常量参数类型并返回结果item1.size()== item2.size()。 size函数是非参数函数,只需要隐藏该参数。有没有办法将这个作为const传递?

问题是,当我尝试在类的const引用使用的大小,这是给我一个错误:

'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&' 

如果我想这个大小将得到的对象为const,我必须使它的朋友和通过该对象作为const refference或有没有办法告诉大小获得类的类型为常量? 感谢您的帮助。

+2

你做了CardDeck :: size()const'吗? – Galik

+0

据我所知,使它的const意味着使其参数为常量,并在这里得到它只有这一点。写常量CardDeck :: size()只意味着返回的值(不是通过引用,而只是它的副本)将是const,这并不意味着什么,我错了吗? 这就是为什么我问是否有办法告诉编译器,这对于方法大小是恒定的。 – KittyT2016

+0

通过在函数声明之后并在其正文之前添加'const'关键字,可以使整个函数为'const'。与返回类型或参数无关。 – Galik

回答

3

最可能是你忘了限定size成员函数为const:size_t size() const { return /* compute/return size */; }

另一种方法是,你真的没有错字CardDeckCardeck地方(从您的错误信息的拼写)。

相关问题