c++类操作符重载

C++ class operator overloading

本文关键字:重载 操作符 c++      更新时间:2023-10-16

可以重载类的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解决方案有点困惑,而且我不完全理解发生了什么,因为它似乎有些模糊。谁能给我解释一下?

你可以写一个operator bool()。这将强制转换为bool类型,使上述语句成为可能。

您重载operator void*(像标准库的iostreams)或使用boost的技巧使用"unspecified_bool_type" typedef(安全bool)。它不会自动反转你的operator!