重载 > 运算符以识别包含字符串的节点
Overloading > operator to recognise nodes containing strings
我编写了一个模板函数来查找两个变量之间的最大值。输入两个字符串时它工作正常。然后我有一个 class 创建包含字符串的 "Nodes" 。我试图在 class 中编写一个重载函数,以便 > 运算符识别这些节点。
这是我的模板函数和我的节点 class。正斜杠后面的行在尝试编译时抛出错误:
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(){
return this->data;
}
friend ostream& operator<<(ostream& os, vector<Node> &v){
for(int i = 0; i < v.size(); i++){
os << v[i].get_data() << ", ";
}
cout << endl;
return os;
}
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;
};
为什么 > 运算符不能在我的 get_data() 函数上工作?
get_data()
不是 const
成员函数,但相关的 operator>
需要 const
引用。不能通过这些引用调用非常量成员函数。您需要让 get_data()
成为 const
成员:
string get_data() const { ....
此外,使用 std::max
而不是推出您自己的最大函数。
我编写了一个模板函数来查找两个变量之间的最大值。输入两个字符串时它工作正常。然后我有一个 class 创建包含字符串的 "Nodes" 。我试图在 class 中编写一个重载函数,以便 > 运算符识别这些节点。
这是我的模板函数和我的节点 class。正斜杠后面的行在尝试编译时抛出错误:
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(){
return this->data;
}
friend ostream& operator<<(ostream& os, vector<Node> &v){
for(int i = 0; i < v.size(); i++){
os << v[i].get_data() << ", ";
}
cout << endl;
return os;
}
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;
};
为什么 > 运算符不能在我的 get_data() 函数上工作?
get_data()
不是 const
成员函数,但相关的 operator>
需要 const
引用。不能通过这些引用调用非常量成员函数。您需要让 get_data()
成为 const
成员:
string get_data() const { ....
此外,使用 std::max
而不是推出您自己的最大函数。