0

各位高手,再次在网上练习的时候,又遇到了一个问题。这是关于功能模板的。我能够创建模板,但我不确定如何重载适当的运算符。请指教。

问题

函数模板maximumOfTree返回相同参数化类型的 3 个元素中的最大值。函数模板可以应用于什么类?编写一个带有name、model、mass字段的trainEngine类。重载适当的运算符,以便将最大的三个函数模板应用于三个trainEngine对象。

至今 ?

 template<class T>
 bool largestOfThree(T t1, T t2, T t3){
  if(t1<t2&&t2<t3){
  return true;
   }else{
    return false;
  }
 }

火车引擎

class trainEngine {
private:
string name;
string model;
string mass;
public:
friend bool operator<(trainEngine const& lhs) {
if (lhs.name<lhs.model&&lhs.model<lhs.mass){
return true;
}

};

4

3 回答 3

3

Afriend operator<将是非成员,因此应该是二进制的。此外,您忘记了返回类型。您可能想要:

friend bool operator<(trainEngine const& lhs, trainEngine const& rhs) {
    // implementation
}

这将转到您的operator<声明当前所在的位置。

是运算符重载的惯用签名列表,以及对 juanchopanza 在评论中提到的内容的更详细解释。请注意,如果非成员运算符被标记为朋友,则可以在类主体中定义它们。(如果你这样做,它们仍然是非成员函数。)

于 2012-12-02T11:26:05.080 回答
0

如果你重载运算符' <',你也应该重载运算符' >'

而且您还必须编写返回类型 bool 。

 friend bool operator<(trainEngine const& obj1, trainEngine const& obj2)

事实上,在大多数代码中,习惯上更喜欢使用<over>但更一般地说,总是重载完整的相关运算符集;在您的情况下,这也可能是==,!=和.<=>=

于 2012-12-02T11:27:17.137 回答
0

请注意,目前您的实现仅取决于右侧(您称之为 lhs!)。这肯定不是你想要的。

我想你想要这样的东西:

bool operator<(trainEngine const& rhs) {
  if(name!=rhs.name) 
    return(name<rhs.name);
  if(model!=rhs.model)
    return (model<rhs.model);
  return (mass<rhs.mass);
}

朋友版本

//within the class
friend bool operator<(trainEngine const& lhs, trainEngine const& rhs);

//outside the class
bool operator<(trainEngine const& lhs, trainEngine const& rhs) {
  if(lhs.name!=rhs.name) 
    return(lhs.name<rhs.name);
  if(lhs.model!=rhs.model)
    return (lhs.model<rhs.model);
  return (lhs.mass<rhs.mass);
}
于 2012-12-02T14:38:58.113 回答