鍍金池/ 問答/C++  HTML/ C++:重載沒有this指針的合法轉換

C++:重載沒有this指針的合法轉換

template <typename T>
class BinarySearchTree {

friend class BinaryNode<T>;

public:
    BinarySearchTree(BinaryNode<T>* rt = nullptr) :
        root(rt) { }
    BinarySearchTree(const BinarySearchTree& rhs);
    ~BinarySearchTree();

    const T& findMin() const;
    const T& findMax() const;
    bool contains(const T& x) const;
    bool isEmpty() const { return root; }
    void printTree();

    void makeEmpty();
    void insert(const T& x);
    void remove(const T& x);

    const BinarySearchTree& operator = (const BinarySearchTree& rhs);

private:
    BinaryNode<T>* root;
    bool contains(const T& x, BinaryNode<T>* rt);
    void insert(const T& x, BinaryNode<T>** rt_ptr);
    void printTree(const BinaryNode<T>* rt);
    void freeTree(BinaryNode<T>* rt);

};

template <typename T>
bool BinarySearchTree<T>::contains(const T& x, BinaryNode<T>* rt) {
    if (rt == nullptr) {
        return false;
    } else if (x < rt->element) {
        contains(x, rt->left_child);
    } else if (x > rt->element) {
        contains(x, rt->right_child);
    } else {
        return true;
    }
}

template <typename T>
bool BinarySearchTree<T>::contains(const T& x) const {
    return contains(x, root);
}

報錯信息:

BinarySearchTree.h: In instantiation of 'bool BinarySearchTree< <template-parameter-1-1> >::contains(const T&) const [with T = int]':
BST_test.cpp:11:33:   required from here
BinarySearchTree.h:129:20: error: passing 'const BinarySearchTree<int>' as 'this' argument discards qualifiers [-fpermissive]
     return contains(x, root);
            ~~~~~~~~^~~~~~~~~
BinarySearchTree.h:115:6: note:   in call to 'bool BinarySearchTree< <template-parameter-1-1> >::contains(const T&, BinaryNode<T>*) [with T = int]'
 bool BinarySearchTree<T>::contains(const T& x, BinaryNode<T>* rt) {
      ^~~~~~~~~~~~~~~~~~~

而VS中報錯是重載沒有this指針的合法轉換,請問大佬這個是出了什么問題,謝謝~

回答
編輯回答
憶當年

As what @felix said in comments: this is BinarySearchTree const * in template <typename T> bool BinarySearchTree<T>::contains(const T& x) const whereas it is BinarySearchTree* in bool contains(const T& x, BinaryNode<T>* rt);

Apparently, it is not allowed to pass BinarySearchTree const* to BinarySearchTree*(this is a implicit parameter in member function), so you can nerve call non-const-qualifier member function from const-qualifier member function.

solution 1:

template <typename T>
bool BinarySearchTree<T>::contains(const T& x) const {
    return const_cast<BinarySearchTree *>(this)->contains(x, root);
}

But this solution will cause undefined behaviour, so another solution is here

This answer may also help you

2018年8月30日 02:23