错误:成员函数不能在其类之外声明

Error: member function may not be declared outside of its class.

本文关键字:声明 成员 函数 不能 错误      更新时间:2023-10-16

我有我的 heap.h 文件,其中包含:

bool insert(int key, double data);

在我的堆CPP.cpp文件中,我有:

 bool heap::insert(int key, double data){
    bool returnTemp;
    node *temp = new node(key, data);
    returnTemp = insert(temp);
    delete temp;
    return returnTemp;
}

但是,我收到一个错误,说"成员函数"heap::insert"可能无法在其类之外重新声明。

您可能忘记了 cpp 中的右括号,这可以解释为在另一个函数中重新声明它。

我有同样的错误消息,但就我而言,问题是由.cpp文件中的分号引起的(来自错误的复制和粘贴)。也就是说,cpp 文件中函数签名的末尾有一个分号。

如果我使用您的代码作为示例,那么,

堆:

bool insert(int key, double data);

heapCPP.cpp:

bool heap::insert(int key, double data);
{
    // ...
}

在堆CPP中修复它.cpp:

bool heap::insert(int key, double data)
{
    // ...
}

错误消息足够清晰。如果函数插入是类堆的成员函数,则应首先在类定义中声明。

例如

class heap
{
    //...
    bool insert(int key, double data);
    //,,,
};

考虑到您正在使用另一个函数,并在第一个函数的主体中插入名称

returnTemp = insert(temp);

所以你似乎对函数声明和定义有些混乱。

我遇到了同样的问题。检查"插入"函数定义前后的函数定义。请确保为以前的函数定义包含右括号。

我的

函数定义嵌套在另一个定义中,这导致了我的错误。

对我来说,同样的错误出现在我从构造函数初始值设定项列表中删除后,它已经过时了。为了提高可读性,构造函数定义的代码格式如下所示:

c_MyClass::c_MyClass()
  : m_bSomeMember{ true }
  , m_bAnotherMember{ false }
{}

我使用的类有更多的初始值设定项,所以当我删除顶部的初始化器时,因为它不再需要,我没有意识到我不小心删除了行首的冒号,只剩下:

c_MyClass::c_MyClass()
  , m_bAnotherMember{ false }
{}

这根本不是构造函数定义并导致错误。

我遇到了同样的错误,然后我发现在我的类中函数声明之后定义成员函数时忘记了半列:

class Fixed{
    private:
        int number;
        static const int fraction = 8;
    public:
        Fixed(const int integer);
        Fixed(const Fixed& obj);
        Fixed(const float number);
        Fixed();
        ~Fixed();
        
        Fixed& operator=(const Fixed& pos);
        int toInt(void) const;
        float toFloat(void) const;
        int getRawBits(void) const;
        void setRawBits(int const raw);
        //extra overloading
        bool operator>(const Fixed& pos) const;
        bool operator<(const Fixed& pos) const;
        bool operator>=(const Fixed& pos) const;
        bool operator<=(const Fixed& pos) const;
        bool operator==(const Fixed& pos) const;
        bool operator!=(const Fixed& pos) const;
        Fixed operator+(const Fixed& pos) const;
        Fixed operator-(const Fixed& pos) const;
        Fixed operator*(const Fixed& pos) const;
        Fixed operator/(const Fixed& pos) const;
        Fixed& operator++(void);
        Fixed operator++(int);
        Fixed operator--(int);
        Fixed& operator--(void);
};

我犯的错误:

Fixed& Fixed::operator--(void);
{
    this->number--;
    return (*this);
}

可以通过删除半列来修复它:

Fixed& Fixed::operator--(void)
{
    this->number--;
    return (*this);
}