我有一个简单的课程
class sample
{
int i;
public:
sample(int i): i(i){}
};
int main()
{
cout << max (12, 26) << endl; // working fine
sample s1(10), s2(20);
cout << max (s1, s2); // lots of compilation errors
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我希望max(s1,s2)应该返回最大max(s1,s2).我知道我错过了一些东西,但却无法想象这些东西.
任何帮助将不胜感激.
Devesh
您有两种选择:首先,实现一个operator<,例如,
bool operator<(const sample& lhs, const sample& rhs)
{
return lhs.i < rhs.i;
}
Run Code Online (Sandbox Code Playgroud)
请注意,在这种特殊情况下,i是private的,所以操作员上方将不得不宣布friend的sample.或者,您可以使用成员1:
class sample
{
// as before ...
bool operator<(const sample& rhs) const { return i < rhs.i; }
};
Run Code Online (Sandbox Code Playgroud)
其次,使用带有二进制比较函子的重载,所以你可以说
std::max(s1, s2, comp);
Run Code Online (Sandbox Code Playgroud)
哪里comp可以是这样的
bool comp(const sample& lhs, const sample& rhs)
{
return lhs.i < rhs.i; // or other logic
}
Run Code Online (Sandbox Code Playgroud)
1非成员是首选,因为它在LHS和RHS之间具有完美的对称性.使用成员时不是这种情况.使用隐式转换构造函数时,这可能是一个问题