C++类运算符重载
可以重载类的 not 运算符:
class TestA
{
public:
bool Test;
const bool operator!(){return !Test;}
};
以便...
TestA A; A.Test = false;
if(!TestA){ //etc }
...可以工作。然而,下面的内容是如何工作的呢?
if(TestA) //Does this have to be overloaded too, or is it the not operator inverted?
我要补充一点,读完它后,我对所采用的 typedef 解决方案感到有点困惑,并且我不完全理解正在发生的事情,因为它似乎有些令人困惑。有人可以将其分解为我可以理解的格式吗?
It's possible to overload the not operator for a class:
class TestA
{
public:
bool Test;
const bool operator!(){return !Test;}
};
So that...
TestA A; A.Test = false;
if(!TestA){ //etc }
...can work. However, how does the following work?
if(TestA) //Does this have to be overloaded too, or is it the not operator inverted?
I will add, having read it, I am slightly confused by the typedef solution that is employed, and I don't fully understand what is occurring, as it seems somewhat obsfucated. Could someone break it down into an understandable format for me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以编写一个
operator bool()
。这会处理 bool 的强制转换,使上述语句成为可能。You could write an
operator bool()
. This takes care of coercion to bool, making statements as your above one possible.您可以重载
operator void*
(如标准库的iostream)或使用boost的技巧,即使用“unspecified_bool_type”typedef
(安全布尔)。它不会自动反转您的运算符!
You overload
operator void*
(like the standard library's iostreams) or use boost's trick of using an "unspecified_bool_type"typedef
(safe bool). It does NOT automatically invert youroperator!