尝试编译时在Eclipse中出现以下错误(C ++)
../CardDeck.cpp:17:22:错误:将“ const CardDeck”作为“ int CardDeck :: size()”的“ this”参数传递而放弃了限定词[-fpermissive]
如果我将int size()方法更改为int size()const,则错误消息已消失并已编译。我不知道为什么?
.H文件如下:
#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);
};
C ++文件是:
#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);
}
}
最佳答案
在副本构造器CardDeck::CardDeck(const CardDeck& rhs)
中,rhs
是对const
CardDeck
对象的引用。
因此,除非将rhs.size()
明确标记为size()
,否则const
将不会编译。那就是您的编译器告诉您的。
最好使代码尽可能const
-正确,因为这样可以防止对类中的成员数据进行错误的更改。实际上,isEmpty()
以及可能的value()
也应标记为const
,所有重载的关系运算符也应标记为。
关于c++ - 有* const *或没有* const *的类方法签名?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35723575/