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

9
我有一个包含以下内容的 heap.h 文件:
bool insert(int key, double data);

在我的 heapCPP.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”成员函数不能在其类外重新声明。

为了确认可能显而易见的事情:heap.h中的函数声明是否在class heap { \* in here *\ };内部? - DavidW
6个回答

17

你可能忘记了在 C++ 中的一个结尾括号,这可能被解释为在另一个函数内重新声明它。


5

我曾经遇到过相同的错误信息,但是我的问题是由于.cpp文件中存在分号(来自于复制和粘贴不当)引起的。也就是说,在cpp文件中函数签名的末尾有一个分号。

如果以你的代码为例,则:

heap.h:

bool insert(int key, double data);

heapCPP.cpp:

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

在 heapCPP.cpp 中使用以下代码修复它:
bool heap::insert(int key, double data)
{
    // ...
}

2
错误信息很清楚。如果insert函数是heap类的成员函数,它应该首先在类定义中声明。
例如:
class heap
{
    //...
    bool insert(int key, double data);
    //,,,
};

请注意,您正在使用名为“insert”的另一个函数,并将其放置在第一个函数的主体内。
returnTemp = insert(temp);

看起来你在函数声明和定义方面有些混乱。


我有:class heap{ public: bool insert(node *x); } - grillo
1
@grillo 但是在类外,您定义了另一个具有相同名称但具有其他参数的函数。 - Vlad from Moscow

0

对我来说,这个错误是在我将构造函数初始化列表中的最顶部初始化器删除后出现的,因为它已经过时了。我的构造函数定义代码格式如下,以便更好地阅读:

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

我所使用的类有更多的初始化程序,因此当我删除顶部的初始化程序时,由于不再需要,我没有意识到我也意外删除了行首的冒号,最终留下了以下代码:
c_MyClass::c_MyClass()
  , m_bAnotherMember{ false }
{}

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


0

我曾经遇到过同样的错误,后来发现在类中函数声明之后定义成员函数时忘记了加分号:

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

0

我曾经遇到过同样的问题。在“插入”函数定义之前和之后检查您的函数定义。确保为先前的函数定义包括闭合括号。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接