用C++写代码:写出下面程序的运行结果,请用增加拷贝构造函数的方法避免存在的回题。#include<iostream> using namespace std; class Vector { public: Vector(int s = 100); int& Elem(int ndx); void Display(); void Set(); ~Vector(); protected: int size; int * buffer; }; Vector::Vector(int s) { buffer = new int[size = s]; for(int i = 0; icsize; i++) buffer[i] = i * i; } int& Vector::Elem(int ndx) { if(ndx < 0 || ndx >= size) { cout << "error in index" << endl; exit(1); } return buffer[ndx]; } void Vector::Display() { for(int j = 0; j < size; j++) cout << Elem(j) << endl; } void Vector::Set() { for(int j = 0; j < size; j++) Elem(j) = j + 1; } Vector::~Vector() { delete[]buffer; } int main() { Vector a(10); Vector b(a); a.Set(); b.Display(); }
时间: 2024-03-03 19:47:33 浏览: 66
程序的运行结果是输出 0-81 的平方。增加拷贝构造函数的方法可以避免回题,也能保证程序的正确性。
修改后的代码如下:
```
#include<iostream>
using namespace std;
class Vector {
public:
Vector(int s = 100);
Vector(const Vector& v); // 添加拷贝构造函数
int& Elem(int ndx);
void Display();
void Set();
~Vector();
protected:
int size;
int* buffer;
};
Vector::Vector(int s) {
buffer = new int[size = s];
for (int i = 0; i < size; i++)
buffer[i] = i * i;
}
Vector::Vector(const Vector& v) { // 拷贝构造函数的实现
size = v.size;
buffer = new int[size];
for (int i = 0; i < size; i++)
buffer[i] = v.buffer[i];
}
int& Vector::Elem(int ndx) {
if (ndx < 0 || ndx >= size) {
cout << "error in index" << endl;
exit(1);
}
return buffer[ndx];
}
void Vector::Display() {
for (int j = 0; j < size; j++)
cout << Elem(j) << endl;
}
void Vector::Set() {
for (int j = 0; j < size; j++)
Elem(j) = j + 1;
}
Vector::~Vector() {
delete[]buffer;
}
int main() {
Vector a(10);
Vector b(a);
a.Set();
b.Display();
return 0; // 添加 return 语句,保证程序的正确性
}
```
输出结果为:
```
1
4
9
16
25
36
49
64
81
```
阅读全文