当解引用运算符(*)被重载时,*this 的使用是否受到影响?
When the dereference operator (*) is overloaded, is the usage of *this affected?
例如,
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
,是否有一种解决方法可以将 *
的用法保持为class?
之外的取消引用运算符
如果我不能在不放弃使用 *this
的情况下重载 *
,那将是一个很大的障碍。
If *this
ends up dereferencing this
to a string instead of a Person
, is there a workaround that maintains the usage of *
as a dereference operator outside the class?
没有。 *this
将是 Person&
或 Person const&
,具体取决于函数。重载适用于 Person
个对象,而不是指向 Person
个对象的指针。 this
是指向 Person
对象的指针。
如果您使用:
Person p;
auto v = *p;
然后,调用 operator*
重载。
要使用 this
调用 operator*
重载,您必须使用 this->operator*()
或 **this
.
您需要 class 的对象而不是指向 class 对象的指针来调用重载的 *
运算符。
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);
例如,
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
,是否有一种解决方法可以将 *
的用法保持为class?
如果我不能在不放弃使用 *this
的情况下重载 *
,那将是一个很大的障碍。
If
*this
ends up dereferencingthis
to a string instead of aPerson
, is there a workaround that maintains the usage of*
as a dereference operator outside the class?
没有。 *this
将是 Person&
或 Person const&
,具体取决于函数。重载适用于 Person
个对象,而不是指向 Person
个对象的指针。 this
是指向 Person
对象的指针。
如果您使用:
Person p;
auto v = *p;
然后,调用 operator*
重载。
要使用 this
调用 operator*
重载,您必须使用 this->operator*()
或 **this
.
您需要 class 的对象而不是指向 class 对象的指针来调用重载的 *
运算符。
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);