C++:当我定义运算符时,所有成员函数都会给出隐式定义错误

C++: All Member Functions Give Implicit Definition Error When I Define Operators

本文关键字:定义 函数 成员 错误 运算符 C++      更新时间:2023-10-16

我有一个数字类可以正常工作:

平均

#ifndef NUMBER_HPP
#define NUMBER_HPP
#include <memory>
class Number
{
private:
     std::unique_ptr<int[]> mDigits;
public:
     // CONSTRUCTORS \
     Number();
};
#endif

编号.cpp

#include "number.hpp"
#define PRECISION 2048
Number::Number()
    :mDigits( new int[PRECISION]() )
{
}

当我添加以下操作员时

平均

#ifndef NUMBER_HPP
#define NUMBER_HPP
#include <memory>
class Number
{
private:
     std::unique_ptr<int[]> mDigits;
public:
     // CONSTRUCTORS \
     Number();
     // CONST OPERATORS \
     bool operator==( Number const& rhs ) const;
     bool operator!=( Number const& rhs ) const;
};
#endif

编号.cpp

#include "number.hpp"
#define PRECISION 2048
Number::Number()
    :mDigits( new int[PRECISION]() )
{
}
bool Number::operator==( Number const& rhs ) const  
{
    for( int i = 0; i < PRECISION; ++i )
        if( mDigits[i] != rhs.mDigits[i] )
            return false;
    return true;
}
bool Number::operator!=( Number const& rhs ) const
{
    return !( *this == rhs );
}

我从GCC 5.4、GCC 6.2和CLANG idk 中得到以下错误

number.cpp:5:16: error: definition of implicitly declared constexpr Number::Number()
Number::Number()
error: number.cpp:12 no bool Number::operator==( const Number& rhs ) const member function declared in class Number

对于类中的每个方法,依此类推。这里发生了什么?

public:
     // CONSTRUCTORS \
     Number();
     // CONST OPERATORS \
     bool operator==( Number const& rhs ) const;
     bool operator!=( Number const& rhs ) const;

预处理器在处理的早期删除所有出现的反斜杠换行符(即行末尾的(。你最终得到的是:

public:
     // CONSTRUCTORS          Number();
     // CONST OPERATORS          bool operator==( Number const& rhs ) const;
     bool operator!=( Number const& rhs ) const;

然后解析为两个注释和一个声明,

     bool operator!=( Number const& rhs ) const;

解决方案:不要将用作一行中的最后一个字符。只需写入// CONSTRUCTORS// CONST OPERATORS

注释中的\\开始一个多行注释(请参阅此处(。这导致这两个函数(默认构造函数和运算符==(的声明实际上是头文件中的注释。