在重载的后缀递增/递减运算符上重载ostream运算符
ostream operator overloading on an overloaded postfix increment/decrement operator
我展示了下面的代码。当我重载重载的后缀运算符时,编译器会抛出错误。它在重载前缀运算符上运行良好。错误
error: no match for ‘operator<<’ in ‘std::cout << cDigit.Digit::operator++(0)’
代码
#include <iostream>
using namespace std;
class Digit
{
private:
int m_nDigit;
public:
Digit(int nDigit=0)
{
m_nDigit = nDigit;
}
Digit& operator++(); // prefix
Digit& operator--(); // prefix
Digit operator++(int); // postfix
Digit operator--(int); // postfix
friend ostream& operator<< (ostream &out, Digit &digit);
int GetDigit() const { return m_nDigit; }
};
Digit& Digit::operator++()
{
// If our number is already at 9, wrap around to 0
if (m_nDigit == 9)
m_nDigit = 0;
// otherwise just increment to next number
else
++m_nDigit;
return *this;
}
Digit& Digit::operator--()
{
// If our number is already at 0, wrap around to 9
if (m_nDigit == 0)
m_nDigit = 9;
// otherwise just decrement to next number
else
--m_nDigit;
return *this;
}
Digit Digit::operator++(int)
{
// Create a temporary variable with our current digit
Digit cResult(m_nDigit);
// Use prefix operator to increment this digit
++(*this); // apply operator
// return temporary result
return cResult; // return saved state
}
Digit Digit::operator--(int)
{
// Create a temporary variable with our current digit
Digit cResult(m_nDigit);
// Use prefix operator to increment this digit
--(*this); // apply operator
// return temporary result
return cResult; // return saved state
}
ostream& operator<< (ostream &out, Digit &digit)
{
out << digit.m_nDigit;
return out;
}
int main()
{
Digit cDigit(5);
cout << ++cDigit << endl; // calls Digit::operator++();
cout << --cDigit << endl; // calls Digit::operator--();
cout << cDigit++ << endl; // calls Digit::operator++(int); //<- Error here??
return 0;
}
您的operator<<
应该通过常量引用获取其Digit
参数:
ostream& operator<< (ostream &out, const Digit &digit)
这里需要这样做,因为Digit::operator++(int)
返回一个临时对象,该对象不能传递给采用非常数引用的函数。
相关文章:
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- <T> 通过模板化运算符重载将 std::complex 乘以双倍
- C++20概念:需要运算符重载
- 使用赋值运算符重载从类中返回jobject
- 在运算符重载定义中使用成员函数(const错误)
- 字节到位运算符重载C++
- 为什么在运算符重载时需要参考?
- 类中 c++ 的运算符 + 重载
- 算术复合运算符重载为非成员
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 交换运算符 + 重载会导致无限递归
- 如何理解新的运算符重载?
- 向量保持复数的运算符重载
- 如何创建运算符重载?
- 链接列表运算符重载没有打印出我想要的内容
- C++:需要帮助了解运算符重载错误
- 使用模板化运算符重载 XOR 运算符失败
- 如何确保接受的C++模板类型使运算符重载?
- 运算符重载使用运算符+添加类模板