Mình có đoạn code sau, mời các bạn xem:
class Array1D {
private:
int n; // so luong phan tu
int *a; // con tro mang 1 chieu
public:
Array1D() {
n = 0;
a = NULL;
}
Array1D(Array1D& x) {
this->n = x.n;
this->a = new int[x.n];
for (int i = 0; i < this->n; i++) {
this->a[i] = x.a[i];
}
}
~Array1D() {
delete[] this->a;
this->a = NULL;
}
friend ostream& operator<<(ostream& os, const Array1D& x) {
for (int i = 0; i < x.n; i++) {
os << x.a[i] << " ";
}
return os;
}
friend istream& operator>>(istream& is, Array1D& x) {
is >> x.n;
x.a = new int[x.n];
for (int i = 0; i < x.n; i++) {
is >> x.a[i];
}
return is;
}
Array1D operator+(Array1D x) {
Array1D re;
re.n = this->n;
re.a = new int[re.n];
for (int i = 0; i < re.n; i++) {
re.a[i] = this->a[i] + x.a[i];
}
return re;
}
void operator=(Array1D x) {
for (int i = 0; i < this->n; i++) {
this->a[i] = x.a[i];
}
}
};
int main() {
Array1D x, y, z;
fstream f1("A.txt", ios::in);
f1 >> x;
f1.close();
fstream f2("B.txt", ios::in);
f2 >> y;
f2.close();
z = x + y;
cout << "x + y: " << z << endl;
x = y;
cout << x << endl;
cout << y << endl;
x.~Array1D();
y.~Array1D();
z.~Array1D();
return 0;
}
/* vd file a.txt có dạng:
4
1 2 3 4
còn file b là
4
2 2 2 2
*/
Khi chương trình chạy tới dòng z = x + y thì liền xuất hiện lỗi (expression block type is valid pHead -> nBlockUse). Mình bó tay luôn không biết sai chỗ nào nữa, các bạn biết chỉ dùm mình đi cám ơn nhiều…