【发布时间】:2012-02-28 05:42:21
【问题描述】:
来自http://www.learncpp.com/cpp-tutorial/142-function-template-instances/
class Cents
{
private:
int m_nCents;
public:
Cents(int nCents)
: m_nCents(nCents)
{
}
friend bool operator>(Cents &c1, Cents&c2) // <--- why friend?
{
return (c1.m_nCents > c2.m_nCents) ? true: false;
}
};
我们也可以这样实现它:
class Cents
{
private:
int m_nCents;
public:
Cents(int nCents)
: m_nCents(nCents)
{
}
bool operator> (Cents& c2) // <---
{
return (this->m_nCents > c2.m_nCents) ? true: false;
}
};
使用第二种实现有什么缺点吗?
【问题讨论】:
-
不要忘记 const 的正确性。
-
在C++-faq中解释得很好
-
如果你必须在布尔表达式上使用
? true : false,那么记住结果也是一个布尔表达式,所以你应该写((c1.m_nCents > c2.m_nCents) ? true : false) ? true : false)。 -
@MikeSeymour 我相信你的意思是
(((c1.m_nCents > c2.m_nCents) ? true : false) ? true : false) ? false == false : true != true。不要让那些布尔表达式远离你。
标签: c++ friend-function