【问题标题】:class method signature with *const* or without *const*?带 *const* 或不带 *const* 的类方法签名?
【发布时间】:2016-03-01 12:57:35
【问题描述】:

在 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);
    }
}

【问题讨论】:

  • for (i=0;i&lt;rhs.size();i++){ 更改为for (i=0;i&lt;rhs.deck.size();i++){,错误应该会消失
  • @jcxz:这只会掩盖真正的问题。
  • 顺便说一句...您的clear 函数太复杂了。只需先完成所有deletes,然后调用deck.clear();
  • @ChristianHackl 我不同意。这只是另一种写法。它不会影响任何东西。 rhs 仍然是 const,无法更改。尽管为错误提供解释可能对 OP 更有利,但这已经在答案中完成了。
  • @jcxz:它通过阻止有用的编译错误消息来掩盖size()const 的设计错误。

标签: c++ constants


【解决方案1】:

在您的复制构造函数CardDeck::CardDeck(const CardDeck&amp; rhs) 中,rhs 是对const CardDeck 对象的引用。

所以rhs.size() 不会编译,除非size() 被明确标记为const。这就是你的编译器告诉你的。

最好将您的代码设置为 const- 尽可能正确,因为这样可以防止错误地更改类中的成员数据。真的,isEmpty() 和可能的 value() 也应该标记为 const,所有重载的关系运算符也应该标记。

【讨论】:

  • ... 以及所有布尔运算符。
  • 使用 const 对象只能运行 const 方法?
  • 当然。您不希望 rhs 被更改,对吗?
  • 知道了,非常感谢您的帮助
猜你喜欢
  • 2022-10-23
  • 1970-01-01
  • 2015-01-20
  • 1970-01-01
  • 2018-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多