操作员过载"equal to"

Operator overloading "equal to"

本文关键字:equal to 操作员      更新时间:2023-10-16

我想为重载C++中等于"="的运算符

class Array
{
    int *p;
    int len;
};

定义了所有函数/构造函数等。

我的问题:有人能给我运算符重载函数的原型吗?假设:

Array a,b;
b=a;

"a"answers"b"中的哪一个将隐式传递,哪一个显式传递?

提前谢谢。

原型是Array& operator=(const Array& that)

在实现这一点时,请记住"三条规则",并充分利用复制和交换习惯用法。

您正在寻找赋值运算符=等于,这是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;
}

请记住,由于您编写了"所有函数/构造函数等都已定义",因此您应该注意您的类需要做什么,并可能按照三规则实现析构函数(和/或查看其在C++11中的变体,可能是相关的,因为没有发布其他代码)。

可能有不止一种方法,但这里有一个选项。

公共功能:

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>来代替。。。