0

我有一个简单的课程

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

我希望 max (s1, s2) 应该返回 max (s1, s2) 的最大值。我知道我错过了一些东西,但无法想象这些东西。

任何帮助将不胜感激。

德韦什

4

2 回答 2

7

您有两个选择:首先,实现一个operator<,例如,

bool operator<(const sample& lhs, const sample& rhs)
{
  return lhs.i < rhs.i;
}

请注意,在这种特殊情况下,iis private,因此上面的运算符必须声明为 a friendof sample。或者,您可以使用成员1

class sample
{
  // as before ...

  bool operator<(const sample& rhs) const { return i < rhs.i; }
};

其次,使用采用二进制比较函子的重载,所以你可以说

std::max(s1, s2, comp);

哪里comp可以像

bool comp(const sample& lhs, const sample& rhs)
{
  return lhs.i < rhs.i; // or other logic
}

1 非成员是首选,因为它在 LHS 和 RHS 之间具有完美的对称性。使用成员时不是这种情况。使用隐式转换构造函数时,这可能是一个问题

于 2013-10-24T09:10:35.523 回答
0
class sample
{

    public:
    int i;
    sample(int i): i(i){}
    bool operator< (const sample& other) const
    {
        return i < other.i;
    }

};

int main()
{  
    sample s1(10), s2(20);
    max (s1, s2); 
    return 0; 
}

const后面注意operator <,很重要。:)

于 2013-10-24T09:14:33.537 回答