C++:当我定义运算符时,所有成员函数都会给出隐式定义错误
C++: All Member Functions Give Implicit Definition Error When I Define Operators
我有一个数字类可以正常工作:
平均
#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
。
注释中的\\开始一个多行注释(请参阅此处(。这导致这两个函数(默认构造函数和运算符==(的声明实际上是头文件中的注释。
相关文章:
- 在命名空间中定义函数还是限定函数
- 为什么在定义函数之前先声明它
- 使用用户定义函数的字符串反转
- 用户定义函数中的指针和输入
- 这个c++代码是如何在没有定义函数的情况下运行的
- 具有外部"c"和程序集的未定义函数
- 已定义函数时出现 G++ "未定义的引用"错误
- 将自定义函数传递到基抽象类中以延迟执行
- C++使用 rand 定义函数语法
- Arduino:在 loop() 和自定义函数中运行相同的代码时出现问题
- 将具有固定签名的自定义函数名称注入 CRTP
- 使用定义函数模板别名
- 是否可以使用单个定义定义函数的常量和常规版本?(使用模板,自动,decltype等)
- 在内联程序集中定义函数和从 C++ 调用时出现问题
- 在 Metal 着色器代码中,如何定义函数的 in/out 参数变量?
- 声明和定义函数静态会产生"undefined reference to function_name()"
- 朋友定义函数的名称空间是什么
- 介子 对用户定义函数的未定义引用
- 如何使用 "using" 关键字定义函数原型/签名
- 在 C 结构中定义C++函数