例如,
class Person{
string name;
public:
T& operator*(){
return name;
}
bool operator==(const Person &rhs){
return this->name == rhs.name;
}
bool operator!=(const Person &rhs){
return !(*this == rhs); // Will *this be the string name or the Person?
}
}
如果*this
最终解除引用this
到string
而不是Person
,是否有一种解决方法可以将*
的使用保留为取消引用班外的操作员?
如果我不放弃*
而不放弃使用*this
,那将是一个很大的障碍。
答案 0 :(得分:40)
如果
*this
最终将this
解除引用到字符串而不是Person
,是否有一种解决方法可以将*
的使用保留为类外的解除引用运算符?
没有。 *this
将为Person&
或Person const&
,具体取决于功能。重载适用于Person
个对象,而不是指向Person
个对象的指针。 this
是指向Person
对象的指针。
如果您使用:
Person p;
auto v = *p;
然后,调用operator*
重载。
要使用operator*
调用this
重载,您必须使用this->operator*()
或**this
。
答案 1 :(得分:12)
您需要类的对象而不是指向类对象的指针来调用重载的*
运算符。
Person *ptr = new Person;
Person p1 = *ptr; // does not invoke * operator but returns the object pointed by ptr
string str = *p1 // invokes the overloaded operator as it is called on an object.
this
指针的情况也是如此。要使用* operator
指针调用this
,您必须取消引用两次:
std::string str = *(*this);