可能重复:
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