2012-12-02 159 views
0

我的专家,再次在网上练习时,我遇到了另一个问题。这是关于函数模板的。我能够创建模板,但我不知道如何重载适当的操作符。请指教。超载运营商<

问题

函数模板largestOfTree返回最大的相同参数化类型的3个元素。函数模板可以应用于什么类?写一个类trainEngine与字段为名称,型号,质量。过载相应的运算符,这样最大的三个函数模板可以应用到三个trainEngine对象。

到目前为止?

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

trainEngine

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; 
} 

};

+0

要哪些类的功能可以应用在很大程度上取决于功能的实现,你没有显示。 – juanchopanza

+0

@juanchopanza我想我可以表明我们可以使用任何类的模板。 –

+0

你在问“功能模板应用到什么类”,我说“这主要取决于函数的实现”。如果该函数只是返回一个'T()',那么它将适用于所有具有默认构造函数和复制构造函数的类。如果调用't1.foo()',那么你会有额外的约束。 – juanchopanza

回答

3

A friend operator<将成为非成员,因此应该是二元的。而且,你忘记了返回类型。你可能想要:

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

这将去你的operator<声明当前的地方。

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

+0

+1。 LHS和RHS之间的对称性最好有一个非成员二元运算符而不是成员。 – juanchopanza

+0

@AntonGolov比我如何编码模板部分。是否正确接受3个参数 –

+0

@ user1571494该模板只是查找哪个“t1”,“t2”和“t3”是最大的。例如,如果't1

0

如果你超载运营商“<”,你也应该重载运算符“>

,你必须写返回类型布尔也。

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

事实上,这是惯例,大多数代码喜欢的<使用过>但更普遍,超载总是一整套相关的运营商;在你的情况下,这也可能是==,!=,<=>=

+0

你的比较函数是一元的,所以它不会工作得很好。 – juanchopanza

+0

@juanchopanza:是的,thnx,更新 –

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); 
}