[英]Is “inline” implicit in C++ member functions defined in class definition
[英]C++: All Member Functions Give Implicit Definition Error When I Define Operators
我這里有一個數字類,可以正常工作:
數字.hpp
#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]() )
{
}
當我添加以下運算符時
數字.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
數字.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
。
注釋中的\\\\將啟動多行注釋(請參見此處 )。 這導致這兩個函數(默認構造函數和operator ==)的聲明實際上是頭文件中的注釋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.