我被困在一个家庭作业问题上,该问题要求我创建/修改一个将两个数组设置为彼此相等的函数。问题是:
“使用复制赋值 (=) 运算符将两个数组设置为彼此相等,这可以通过以下方式检查:
y = x;
cout << "x equals y? " << (x == y) << endl; //Should return "True"
并在以下规则中设置:
“请注意,只有当两个 Array 对象具有相同的长度和相同的元素值时,它们才应被视为相等。”
这是我的代码,我已经实现了两个调试部分,这表明它们在赋值函数和主函数中确实相等,所以我最好的猜测是长度不匹配。我不允许修改提供的任何代码(所有类和函数的东西,或 main 中调试器之上的任何东西),所以我不确定如何将长度设置为彼此相等以满足条件(x==y)
#include <iostream>
using namespace std;
// definition
#define MAX_LENGTH 100
#define INIT_VALUE 0
class Array {
public:
Array(int length);
Array& operator=(const Array& other);
int length() const;
int& operator[](int index);
bool operator==(const Array& other) const;
bool operator!=(const Array& other) const;
private:
int length_;
int elements_[MAX_LENGTH];
};
// implementation
Array::Array(int length) {
length_ = length;
if (length_ > MAX_LENGTH) length_ = MAX_LENGTH;
for (int i = 0; i < length_; ++i) {
elements_[i] = INIT_VALUE;
}
}
Array& Array::operator=(const Array& other)
{
/*DEBUG*/cout << endl << endl << "<<NOW IN ASSIGNMENT FUNCTION>>" << endl << endl;
for (int i = 0; i < other.length_; ++i)
{
elements_[i] = other.elements_[i];
/*DEBUG*/cout << endl << "Elements: " << elements_[i] << " | Other Elements: " << other.elements_[i] << endl;
}
return *this;
}
int Array::length() const {
return length_;
}
int& Array::operator[](int index) {
// Q3 code goes here
return elements_[index];
}
bool Array::operator==(const Array& other) const
{
if (length_ != other.length_) return false;
for (int i = 0; i < other.length_; ++i) {
if (elements_[i] != other.elements_[i]) return false;
}
return true;
}
bool Array::operator!=(const Array& other) const
{
if (length_ != other.length_)
{
return true;
}
for (int j = 0; j < other.length_; ++j)
{
if (elements_[j] != other.elements_[j]) return true;
}
return false;
}
// testing
int main()
{
Array x(10);
x[3] = 42;
cout << "x contains ";
for (int i = 0; i < x.length(); ++i) {
cout << x[i] << " ";
}
cout << endl;
Array y(5);
cout << boolalpha;
cout << "x equals y? " << (x == y) << endl;
cout << "x notequals y? " << (x != y) << endl;
y = x;
//DEBUG SECTION
cout << endl << endl << "<<NOW IN MAIN>>" << endl << endl;
for (int i = 0; i < x.length(); ++i)
{
cout << endl << "Elements: " << x[i] << " | Other Elements: " << y[i] << endl;
}
//END OF DEBUG SECTION
cout << "x equals y? " << (x == y) << endl;
}
所以问题是,我怎样才能让这些数组具有相同的长度而不在'main'中修改它们?我可以通过赋值函数来完成吗?
最佳答案
您只是忘记在 Array::operator=
中分配相同的长度。
这可以通过在
中编写this->length_ = other.length_;
来完成
Array& Array::operator=(const Array& other)
在覆盖数组之前。
关于c++ - 作业任务 : Checking the equality of two arrays,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52059481/