简体   繁体   中英

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

I have a number class here that works properly:

number.hpp

#ifndef NUMBER_HPP
#define NUMBER_HPP

#include <memory>

class Number
{
private:
     std::unique_ptr<int[]> mDigits;
public:
     // CONSTRUCTORS \\
     Number();
};

#endif

number.cpp

#include "number.hpp"

#define PRECISION 2048

Number::Number()
    :mDigits( new int[PRECISION]() )
{
}

When I add the following operators

number.hpp

#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

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

I get the following error from GCC 5.4, GCC 6.2, and 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

And so on for every method in the class. What is happening here?

public:
     // CONSTRUCTORS \\
     Number();

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

The preprocessor removes all occurrences of backslash-newline (ie \\ at the end of a line) very early in processing. What you end up with is:

public:
     // CONSTRUCTORS \         Number();

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

Which is then parsed as two comments and one declaration,

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

Solution: Don't use \\ as the last character in a line. Just write // CONSTRUCTORS or // CONST OPERATORS .

The \\\\ in your comments starts a multi-line comment (see here ). This causes the declarations of those two functions (the default constructor and operator==) to really be comments in the header file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM