在函数的返回值上使用运算符时,运算符重载函数不起作用
Operator overloading function not working when using the operator on return value of a function
我有一个简单的Node类,它可以创建节点并访问这些节点中的字符串。我在类中有两个运算符重载函数,以便能够比较节点(>overloader)并打印它们的数据(<<overloadr)。还有内置的max()函数的模板副本。我的两个运算符重载都可以正常工作,除非我试图打印以两个节点为参数的max()函数的返回值。这是我的代码:
#include <iostream>
#include <vector>
using namespace std;
template<typename T>
T maximum(const T& a, const T& b){
return a > b ? a : b;
}
class Node{
public:
Node(const string& s = "Default"):
data(s){
}
string get_data() const {
return this->data;
}
friend ostream& operator << (ostream& os, Node& a){
return os << a.get_data();
}
friend bool operator > (const Node& a, const Node& b){
if(a.get_data() > b.get_data()){
return true;
}
else return false;
}
private:
string data;
Node* next;
};
int main() {
double d1 = 0.1, d2 = 0.2;
cout << maximum(d1, d2) << endl;
string s1 = "woody", s2 = "buzz";
cout << maximum(s1, s2) << endl;
Node a("buzz"), b("woody");
cout << maximum(a, b) << endl;
return 0;
}
问题出在main()函数的最后一行。我的编译器抛出一条错误消息,内容类似于cannot bind ostream<char> value to ostream<char>&&
将const
添加到operator<<
:的第二个参数
friend ostream& operator << (ostream& os, const Node& a){
^^^^^
相关文章:
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 在 C++ 中调用类中的运算符函数
- 错误 C2676:std::set::const_iterator 没有运算符 + 函数?
- 为什么 ADL 的运算符函数行为与其他函数不同?
- 将内置类型变量传递给只有一个类类型参数的"+"运算符函数时自动类型转换的构造函数
- 第二个常量在运算符函数中做什么?
- 重载赋值运算符函数和复制构造函数中的错误
- 内置类型的运算符函数
- 如何调用运算符函数添加两个对象?
- Const 仍然允许在运算符函数 c++ 下进行更改
- 在呼叫运算符函数const中调用运算符时错误
- 是否有一种方法可以在超载运算符函数中接触默认运算符函数
- 重载时获取堆栈溢出 >> 运算符函数是为类调用的。我需要进行哪些更改?
- 运算符 [] 函数的实现是如何工作的
- C++:使用父类运算符函数更新子类对象的继承变量
- 创建一个接受 2 个输入参数的文本运算符函数
- 为什么找不到重载运算符函数?
- 为什么auto_ptr中有模板复制构造函数和覆盖运算符函数
- 为什么某些C++标准库“运算符<<”函数将其流宽度重置为 0
- C++SFINAE运算符/函数结果类型检查