gpt4 book ai didi

c++ - 运算符(operator)重载功能不起作用

转载 作者:行者123 更新时间:2023-12-01 14:52:33 30 4
gpt4 key购买 nike

我有一个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) << " , ";
}


最佳答案

除了copyt构造函数外,请注意

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

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

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

关于c++ - 运算符(operator)重载功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62195704/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com