当解除引用运算符(*)过载时,* this的使用是否受到影响?

时间:2017-06-06 03:07:16

标签: c++ pointers operator-overloading this dereference

例如,

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最终解除引用thisstring而不是Person,是否有一种解决方法可以将*的使用保留为取消引用班外的操作员?

如果我不放弃*而不放弃使用*this,那将是一个很大的障碍。

2 个答案:

答案 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);