class method signature with *const* or without *const*?

五迷三道 提交于 2020-07-24 04:34:28

问题


I get the following error in Eclipse when trying to compile (c++)

../CardDeck.cpp:17:22: error: passing ‘const CardDeck’ as ‘this’ argument of ‘int CardDeck::size()’ discards qualifiers [-fpermissive]

if I change int size() method to int size() const the error msg is gone and its compiled. I dont know why ?

the .H file is the following :

  #include "Card.h"
#include <vector>

using namespace std;
class CardDeck{
    private:
        vector<Card*> deck;

    public:

        int size();
        CardDeck();
        CardDeck(const CardDeck& rhs);
        CardDeck& operator=(const CardDeck& rhs);
        Card& draw();
        Card& top();

        bool isEmpty();
        void clear();
        int value();
        CardDeck& operator+=(const CardDeck& rhs); /// not sure if to return ref
        CardDeck& operator+(const CardDeck& rhs);
        friend CardDeck&  operator*(unsigned int num,CardDeck& rhs);
        friend CardDeck&  operator*(CardDeck& lhs,unsigned int num);
        bool operator<=(const CardDeck& rhs );
        bool operator>=(const CardDeck& rhs);
        bool operator<(const CardDeck& rhs);
        bool operator>(const CardDeck& rhs);
        bool operator==(const CardDeck& rhs);
        bool operator!=(const CardDeck& rhs);
        Card*  operator[](int i);
};

and the C++ file is :

#include "CardDeck.h"
int CardDeck::size() {
    return this->deck.size();
}
CardDeck::CardDeck(){};
CardDeck::CardDeck(const CardDeck& rhs){
    this->clear();
    int i;
    for (i=0;i<rhs.size();i++){
        Card* current_card = rhs.deck[i];
        Card* new_copy = new Card(*current_card);
        this->deck.push_back(new_copy);
    }


}
Card* CardDeck::operator[](int i) {
    return this->deck[i];
}



void CardDeck::clear(){
    vector<Card*>::iterator it ;
    for(it=this->deck.begin();it != this->deck.end();++it){
        Card* temp = *it;
        this->deck.erase(it);
        delete(temp);
    }
}

回答1:


In your copy constructor CardDeck::CardDeck(const CardDeck& rhs), rhs is a reference to a const CardDeck object.

So rhs.size() will not compile unless size() is explicitly marked as being const. That's what your compiler is telling you.

It's good practice to have your code as const-correct as possible as this prevents errant changes to the member data in a class. Really, isEmpty(), and possibly value() should be marked const too, as should all the overloaded relational operators.



来源:https://stackoverflow.com/questions/35723575/class-method-signature-with-const-or-without-const

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!