reference to non-static member function must be called!

2,691 阅读2分钟

今天在做牛客网的一个编程题的时候,出现了这个问题:reference to non-static member function must be called!

代码如下:

class Solution {
public:
    TreeNode* KthNode(TreeNode* pRoot, int k)
    {
        fun(pRoot);   //先序遍历
        int len = num.size();
        if(len == 0 || k > len)
            return NULL;
        sort(num.begin(),num.end(),com);    //排序
        for(int i=0;i<k;i++)
        {
            if(i == k-1)
                return num[k-1];
        }
        return NULL;
    }
 
    //先序遍历的非递归实现
    void fun(TreeNode* pRoot)
    {
        stack<TreeNode*> s;//辅助栈
        TreeNode* pNode = pRoot;
        while(pNode)
        {
            s.push(pNode);
            num.push_back(pNode);   //保存节点
            pNode = pNode->left;    //往左子树转移
        }
         
        while(!s.empty())
        {
            TreeNode* tempNode = s.top();  //取当前栈顶元素
            s.pop();
            if(tempNode->right)   //如果有右子树
            {
                TreeNode* t = tempNode->right;
                while(t)
                {
                    num.push_back(t);   //保存当前节点右子树
                    s.push(t);
                    t = t->left;   //往左子树转移
                }
            }
        }
    }
     
    static bool com(TreeNode* p1,TreeNode* p2)    //谓词
    {
        return p1->val < p2->val;
    }
public:
    vector<TreeNode*> num;   //存储先序遍历
};

首先说明问题意思:这个问题是指你引用(调用)了非静态函数,但你不是通过类对象来调用的。问题的来源就是sort()函数的第三个谓词参数。为什么会是这样的呢?

按照常理来说,同一个类的非静态const成员函数中能相互调用,而不用通过类对象进行访问,为什么这里不行呢?相反如果我们把谓词函数com()定义为static函数问题就没有了。

**问题的原因其实就是函数参数不匹配的问题。因为我们普通的成员函数都有一个隐含的this指针,表面上看我们的谓词函数com()只有两个参数,但实际上它有三个参数,而我们调用sort()排序函数的时候只需要用到两个参数进行比较,所以就出现了形参与实参不匹配的情况(函数有三个形参,但是只输入了两个实参)。

所以,解决办法就是把谓词函数com()定义为static成员函数。**