gpt4 book ai didi

c++ - 重载 > 运算符以识别包含字符串的节点

转载 作者:行者123 更新时间:2023-11-28 02:17:50 25 4
gpt4 key购买 nike

我编写了一个模板函数来查找两个变量之间的最大值。输入两个字符串时它工作正常。然后我有一个创建包含字符串的“节点”的类。我试图在类中编写一个重载函数,以便 > 运算符识别这些节点。

这是我的模板函数和我的 Node 类。正斜杠后面的行在尝试编译时抛出错误:

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 而不是推出您自己的最大值函数。

关于c++ - 重载 > 运算符以识别包含字符串的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33510177/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com