2017-06-06 39 views
27

例如,当解除引用运算符(*)超载时,是否会影响*的使用?

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而不能超载*将是一个相当大的障碍。

+23

超载适用于Person对象。但是'this'是一个人*指针*。 – Galik

+1

@Galik这个评论应该是一个(接受的)答案。 – YSC

回答

41

如果*this最终取消引用this为一个字符串,而不是一个Person,是否有维护的*使用作为类外引用操作解决方法?

No. *this将根据功能Person&Person const&。超载适用于Person对象,而不适用于指向Person对象的指针。 this是指向Person对象的指针。

如果你使用:

Person p; 
auto v = *p; 

然后,operator*过载被调用。

要使用this调用operator*过载,您必须使用this->operator*()**this

+3

建议您在答案中加入@ Galik的解释。 – einpoklum

+0

@einpoklum,极好的建议。 –

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指针的情况也是如此。与this指针调用* operator,你将不得不取消引用两次:

std::string str = *(*this);