操作员重载功能不起作用

时间:2020-06-04 13:21:40

标签: c++ operator-overloading

我有一个Array类,该类具有将值设置为数组索引或获取数组索引值的功能,我想制作一个重载运算符函数以添加两个Arrays对象,结果是每个元素一个数组是其他两个数组的相同索引元素的总和,例如: 数组A = {1,4,6},数组B = {1,20,3} c = A + B // c = {1 + 1,4 + 20,6 + 3}。 问题是在“求和数组”对象中,我得到的是一些随机值,而不是总和值,我认为它们是某些地址,原因是我的重载函数无法正常工作。

public:

    Array(int asize)
        :size(asize)
    {

        Arr = new int[size];
    }
Array(const Array &other) {
        size = other.size;
        Arr = new int[other.size];//
        for (int x = 0;x < other.size - 1;x++)
            Arr[x] = other.Arr[x];
    }
 Array operator+(const Array &other) {
        Array t(*this);// creating new array with the values of the left hand Array


        int ssize = (other.size < size) ? other.size : size;//if the right hand array size is 
        for (int x = 0;x < ssize;x++)                            //smaller than the left side(choose the smallest size)     
        {
            t.Arr[x] += other.Arr[x];
        }

        return t;
    }

    ~Array() {
        delete[] Arr;
    }
    int get(int index) {
        return Arr[index];
    }
    void set(int index, int value) {
        Arr[index] = value;
    }

    int getSize() {
        return size;
    }
    Array operator+(const  Array  &rhs)  {//I also tried without const and without & sign
        Array H(this->getSize());
        for (int i = 0;i < this->getSize();i++)
        {
            H.Arr[i] = rhs.get(i)+this->get(i);//or rhs.Arr[i]+this->Arr[i];
            }
        return H;
    }


private:
    int size;
    int *Arr;


     }; 

这是我的主要功能:

std::cout << "\n enter the size of the Array" << std::endl;
    int Size1;
    std::cin >> Size1;
    Array A1(Size1);
    std::cout << "insert the elements starting of the first element of the Array" << std::endl;
    int E1;
    for (int i = 0;i < Size1;i++) {
        std::cout << "Element number" << i + 1 << " is: " << std::endl;

        std::cin >> E1;
        A1.set(i, E1);

    }


    std::cout << "\nenter the size of the Array 2" << std::endl;
    int Size2;
    std::cin >> Size2;
    Array A2(Size2);
    std::cout << "insert the elements starting of the first element of the Array" << std::endl;
    int E2;
    for (int i = 0;i < Size2;i++) {
        std::cout << "Element number" << i + 1 << " is: " << std::endl;

        std::cin >> E2;
        A2.set(i, E2);

    }

    Array sum(2);// I am currently trying with only 2 elements Arrays just to check if its working
    sum = A1 + A2;
    for (int i = 0;i < Size2;i++) {
        std::cout << sum.get(i) << " , ";
    }


1 个答案:

答案 0 :(得分:1)

除copyt构造函数外,请注意

 Array sum(2);// I am currently trying with only 2 elements Arrays just to check if its working
    sum = A1 + A2;

这意味着您还需要定义operator =才能使代码正常工作。

顺便说一句,如果您写:Array sum(A2 + A2);而不是这两行,这也可以在没有operator =的情况下使用。

相关问题