代码之家  ›  专栏  ›  技术社区  ›  Jake Wright

操作员问题=

c++
  •  0
  • Jake Wright  · 技术社区  · 5 年前

    我建了两个班, 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
    };
    

    这是Array的头部:

    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;
    }
    

    如果 mul1 {1, 2, 3} set(当然长度为3)和 mul2 {-2, 2, 5 9} ,代码:

    Multime mul5;
    mul5=mul1*mul2;
    

    输出

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

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

    0 回复  |  直到 5 年前
        1
  •  1
  •   1201ProgramAlarm    5 年前

    由于末尾的这一行,您得到了所做的输出 operator* :

    *this=q;
    

    您正在覆盖 this 参数(即 mul1 来自呼叫者),它不是空的 Multime 对象。

    从根本上说,你的两个 操作员* 不作为乘法运算符,因为它修改了其中一个参数。它的行为是 operator*= 功能。会员签名 操作员* 通常类似于

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

    它不会修改任何一个参数,并返回一个新对象。你可以从末尾删除有问题的作业,然后用 return q; .