C++ 操作员的问题=

C++ 操作员的问题=,c++,C++,我构建了两个类,Multime(意思集)和Array。我需要重载*操作符来进行集合交集并将结果分配给另一个集合。我决定也重载=操作符,以解决后者。这是Multime的标题: class Multime{ private: Array a; int* n; public: Multime(); Multime(Multime& ob); ~Multime(); void Transformare(Array t);//transforms a

我构建了两个类,
Multime
(意思集)和
Array
。我需要重载
*
操作符来进行集合交集并将结果分配给另一个集合。我决定也重载
=
操作符,以解决后者。这是Multime的标题:

class Multime{
private:
    Array a;
    int* n;
public:
    Multime();
    Multime(Multime& ob);
    ~Multime();
    void Transformare(Array t);//transforms an array into a set by eliminating duplicates
    int& operator[] (int x);//makes ob[i] return ob.a[i];
    Multime& operator+ (Multime& y);
    Multime& operator=(Multime& y);
    Multime& operator* (Multime& y);
    void Afisare();//outputs the array in the object that called it
};
这是数组的标头:

class Array{
private:
    int* c;///the array
    int len, capacity;
public:
    Array();
    void Append(int);
    ~Array();
    int& operator[] (int);//makes ob[i] retuen ob.c[i]
    void Afisare();
    void Sortare();//sorts the array
    friend class Multime;
};
这就是我重载=运算符的方式:

Multime& Multime::operator=(Multime& ob)
{
    if(*n!=0) { 
        std::cout<<"don't overwrite a nonvoid set"; 
        std::cout<<"the result should have been "<<ob.Afisare(); 
        std::cout<<"n="<<*n;
    }
    else
    {
        if(this!=&ob)
        {
            for(int i=0; i<*ob.n; i++)
            {
                a.Append(ob.a[i]);
            }
            *n=*(ob.n);
        }
    }
    return *this;
}
Multime& Multime::operator* (Multime& y)
{
    Multime q;
    for(int i=0; i<*n; i++)
    {
        for(int j=0; j<*y.n; j++)
        {
            if(a[i]==y.a[j])
                q.a.Append(a[i]);
        }
    }
    *q.n=q.a.len;
    *this=q;
    return *this;
}
输出

don't overwrite a nonvoid set
the result should have been 2 
n=3

我很困惑为什么
n
3
,尽管它是刚刚创建的。

由于
操作符*
末尾的这一行,您得到了输出:

*this=q;
您正在覆盖
this
参数(调用者提供的
mul1
),该参数不是空的
Multime
对象

基本上,您的两个
运算符*
的行为不象乘法运算符,因为它修改了其中一个参数。它的行为是一个
操作符*=
函数。成员
运算符*
的签名通常类似于

Multime Multime::operator*(const Multime& y) const

其中它不会修改任何一个参数,并返回一个新对象。您可以从末尾删除有问题的赋值,只需使用
return q

请显示重现问题所需的所有代码。请给我看看;多重ME(多重ME&ob)`构造函数为什么
multimen::n
是指针?它指向什么?看看如何创建一个。您还没有显示所有相关的代码(如构造函数)。这个答案解决了眼前的问题,但还有其他问题潜伏着。
Multime Multime::operator*(const Multime& y) const