我想重載等於「=」運算符在C++對操作符重載「等於」
class Array
{
int *p;
int len;
};
所有功能/構造等被定義。我的問題: 有人可以給我的運算符重載函數的原型嗎? 並假設:
Array a,b;
b=a;
其中的「A」和「B」將被隱式通過,其中明確?
在此先感謝。
我想重載等於「=」運算符在C++對操作符重載「等於」
class Array
{
int *p;
int len;
};
所有功能/構造等被定義。我的問題: 有人可以給我的運算符重載函數的原型嗎? 並假設:
Array a,b;
b=a;
其中的「A」和「B」將被隱式通過,其中明確?
在此先感謝。
原型是Array& operator=(const Array& that)
。
在執行此操作時,請記住關於rule of three並充分利用copy-and-swap idiom。
可能有多種方法可以做到這一點,但這裏有一個選項。
公共職能:
Array::Array(const Array& array)
{
Allocate(0);
*this = array;
}
Array::~Array()
{
Deallocate();
}
const Array& Array::operator=(const Array& array)
{
if (this == &array)
return *this;
Deallocate();
Allocate(array.len);
for (int i=0; i<len; i++)
p[i] = array.p[i];
return *this;
}
非公共職能:
void Array::Allocate(int size)
{
len = size;
if (len > 0)
p = new int[len];
}
void Array::Deallocate()
{
if (len > 0)
delete[] p;
len = 0;
}
當然,你可以隨時使用vector<int>
,而不是...
你尋找賦值運算符=(不等於到,這是operator==
,通常作爲一個平等的比較)
class Array
{
int *p;
int len;
public:
// Assignment operator, remember that there's an implicit 'this' parameter
Array& operator=(const Array& array)
{
// Do whatever you want
std::cout << "assignment called";
return *this;
}
};
int main(void) {
Array a, b;
a = b;
}
請記住,因爲你寫了「/構造等的定義所有功能」,你應該注意什麼你需要你的類來做,也可能實現析構函數,如rule of three(和/或看看它在C++ 11中的變體,可能是相關的,因爲沒有其他代碼發佈)。
**等於**運算符是'operator ==',而不是'operator ='。你想要的是**賦值**運算符。 – 2014-10-18 07:14:15
[運算符重載]可能重複(http://stackoverflow.com/questions/4421706/operator-overloading) – juanchopanza 2014-10-18 07:37:10
我的不好。 :P賦值運算符。不等於 :) – 2014-10-18 11:48:51