这是在Windows 7下最新的QT IDE (boost.1.48)上运行的
class Employee {
public:
int Id;
...
bool operator==(const Employee& other) {
qDebug() << this->Id << ":" << "compare with " << other.Id;
return this->Id==other.Id;
}
}
测试代码:
Employee jack1;
jack1 == jack1; // the operator== gets invoked.
shared_ptr<Employee> jack(new Employee);
jack == jack; // the operator== doesn't get invoked.
boost头文件中的相关代码为:
template<class T, class U> inline bool operator==(shared_ptr<T> const & a, shared_ptr<U> const & b)
{
return a.get() == b.get();
}
它似乎在进行指针比较,而不是按照我的预期进行。
我做错了什么?
最佳答案
shared_ptr
是一个类似指针的类(它模拟具有额外功能的指针)因此 operator==
for shared_ptr
比较指针。
如果你想比较指向的对象,你应该使用 *jack == *jack
,就像普通指针一样。
关于c++ - Boost shared_ptr 似乎不支持运算符 ==,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8661791/