可能重複:
What are the differences between pointer variable and reference variable in C++?
What are the distinctions between the various symbols (*,&, etc) combined with parameters?混淆引用和指針
我有一點麻煩讓我的頭周圍粘貼下面這個例子的代碼。具體來說,功能Buf& operator=(const Buf &);
。據我所知,這個函數需要返回類Buf
的對象的地址。出現了兩個問題:
是否同樣適用於這個聲明爲
Buf* operator=(const Buf*);
,因爲Buf*
也Buf
類的一個實例的地址?如果不是,爲什麼不呢?如果是這樣,它只是編碼模式的首選?哪個更好?在相應的函數定義中,返回
*this
。據我所知,this
是一個指針或地址對應的Buf
類的對象。因此*this
是指針指向的內容,即類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(); }
這裏有您需要的'*''主場迎戰&'回答:http://stackoverflow.com/a/9637342/365496 – bames53 2012-04-11 13:27:24