在重载I/O运算符内部重载增量运算符时出错
Error while overloading increment operator inside overloaded I/O operator
我是OOPS概念的初学者。我现在正在处理操作员过载问题。当我在cout
中使用重载的增量运算符时,我遇到了错误no match for operator<<
。当我从cout中删除重载的增量时,它工作得很好。从逻辑上讲,我不觉得代码有什么问题。不过,我不知道为什么我会出错?下面是我的代码,以便更好地理解这个问题。
#include <iostream>
using namespace std;
class Digit
{
private:
int digit;
public:
Digit(int n)
{
digit = n;
}
Digit& operator++();
Digit operator++(int); //overloaded postfix increment. Dummy argument used
Digit& operator--();
Digit operator--(int); //overloaded postfix decrement. Dummy argument used
friend ostream& operator<<(ostream& out, Digit& x); //overloaded << prototype
int GetDigit()
{
return digit;
}
};
Digit Digit::operator++(int)
{
//Create a temporary object with a variable
Digit temp(digit);
//Use prefix operator to increment this Digit
++(*this);
return temp; //return temporary result
}
Digit& Digit::operator++()
{
if (digit==9)
digit = 0;
else
++digit;
return *this;
}
Digit Digit::operator--(int)
{
//Create a temporary object with a variable
Digit temp(digit);
//Use prefix operator to increment this Digit
--(*this);
return temp; //return temporary result
}
Digit& Digit::operator--()
{
if (digit==0)
digit = 9;
else
--digit;
return *this;
}
int main()
{
using namespace std;
Digit n(9);
Digit x(0);
cout << n++ << endl;
cout << x-- << endl;
return 0;
}
ostream& operator<<(ostream& out, Digit& x)
{
out << x.digit;
return out;
}
main()
内部的线路cout << n++ << endl; cout << x-- << endl;
导致错误。
这是因为后缀运算符通过值返回,如果不保存该值,则会有一个临时的,并且非常量引用无法绑定到临时引用。
简单的修复方法是让您的输出操作符通过const
引用接受Digit
参数:
ostream& operator<<(ostream& out, Digit const& x)
// ^^^^^
相关文章:
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 重载运算符new[]的行为取决于析构函数
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 在 myVector 类中重载运算符 + 时出错
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 如何在 cpp 中重载运算符 +=?
- C++ 如何重载 [] 运算符并进行函数调用
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 重载运算符有地址吗?
- 如何迭代重载运算符 [] 的类?
- 重载运算符与添加问题
- 模板基类中的重载运算符
- 如何调用用于重载运算符"<<"的 friend 函数?
- 在 C++17 中的命名空间和子命名空间中重载运算符是不明确的
- 重载运算符<<采用谷歌 C++ 风格
- C++ 如何正确重载 + 运算符
- cout (<<) 重载运算符不打印减去的矩阵
- 如何在 c++ 中重载运算符 + 以便能够 whrite c_str = "smth" + c_str;
- 重载运算符*以获取对另一个类的实例的引用