我很难理解下面粘贴的这个示例代码。具体来说,函数Buf& operator=( const Buf & );
。据我了解,此函数需要Buf
返回类对象的地址。出现两个问题:
将 this 声明为 是否同样适用
Buf* operator=( const Buf* );
,因为Buf*
它也是类实例的地址Buf
?如果不是,为什么不呢?如果是这样,它只是编码风格的偏好吗?哪个更可取?在对应的函数定义中,
*this
返回。据我了解,this
是一个指针,或对应于 class 对象的地址Buf
。*this
指针指向的也是如此,即 class 的对象Buf
。这和退货有冲突Buf*
吗?函数应该返回this
而不是返回*this
吗?
我想我今天有这样的日子......请有人帮忙!
using namespace std; class Buf { public: Buf( char* szBuffer, size_t sizeOfBuffer ); Buf& operator=( const Buf & ); void Display() { cout << buffer << endl; } private: char* buffer; size_t sizeOfBuffer; }; Buf::Buf( char* szBuffer, size_t sizeOfBuffer ) { sizeOfBuffer++; // account for a NULL terminator buffer = new char[ sizeOfBuffer ]; if (buffer) { strcpy_s( buffer, sizeOfBuffer, szBuffer ); sizeOfBuffer = sizeOfBuffer; } } Buf& Buf::operator=( const Buf &otherbuf ) { if( &otherbuf != this ) { if (buffer) delete [] buffer; sizeOfBuffer = strlen( otherbuf.buffer ) + 1; buffer = new char[sizeOfBuffer]; strcpy_s( buffer, sizeOfBuffer, otherbuf.buffer ); } return *this; } int main() { Buf myBuf( "my buffer", 10 ); Buf yourBuf( "your buffer", 12 ); // Display 'my buffer' myBuf.Display(); // assignment opperator myBuf = yourBuf; // Display 'your buffer' myBuf.Display(); }