在函数的 return 值上使用运算符时,运算符重载函数不起作用
Operator overloading function not working when using the operator on return value of a function
我有一个简单的节点 class,它可以创建节点并可以访问这些节点内的字符串。我在 class 中有两个运算符重载函数,以便能够比较节点(> 重载器)并打印它们的数据(<< 重载器)。还有内置 max() 函数的模板副本。我的两个运算符重载器都按它们应有的方式工作,除非我尝试使用两个节点作为参数打印 max() 函数的 return 值。这是我的代码:
#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){
^^^^^
我有一个简单的节点 class,它可以创建节点并可以访问这些节点内的字符串。我在 class 中有两个运算符重载函数,以便能够比较节点(> 重载器)并打印它们的数据(<< 重载器)。还有内置 max() 函数的模板副本。我的两个运算符重载器都按它们应有的方式工作,除非我尝试使用两个节点作为参数打印 max() 函数的 return 值。这是我的代码:
#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){
^^^^^