gpt4 book ai didi

c++ - 在这种情况下,在 'this' 前面加一个星号有什么作用?

转载 作者:太空宇宙 更新时间:2023-11-04 16:16:30 26 4
gpt4 key购买 nike

我想知道在重载“!=”运算符的这种特殊情况下,在“this”前面放一个星号有什么作用。

class String
{
private:
int m_length;
char *m_strPtr;

//Utility function
void set_string( const char *string );

public:
String( const char *string ); // Default constructor
String( const String &string ); // Copy constructor
~String();

int get_length() const { return m_length; };

// Overloaded operators
bool operator!=( const String &rhs ) const { return !( *this == rhs ); };
bool operator==( const String &rhs ) const { return ( strcmp( m_strPtr, rhs.m_strPtr ) == 0 ); };

};

在这种情况下为什么要使用“*this”而不是“this”?

最佳答案

使用 *this 通过所谓的解引用 返回对对象的实际引用。在取消引用之前,this 是一个指针。使用 *this 为您提供“内容”当前对象

Pointers/Dereference Link

仅供引用:只是为了让 *& 运算符更加清晰,以供您将来解决其他问题时引用

*var ...Means "content of" var

int* ...Means int pointer

&int ...Means address of int

int& ...Means int address

关于c++ - 在这种情况下,在 'this' 前面加一个星号有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22124216/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com