问题 问答题

请使用VC6或使用[答题]菜单打开考生目录proj3下的工程文件proj3,此工程中包含一个源程序文件proj3.cpp,其功能是从文本文件in.dat中读取全部整数,将整数序列存放到intArray类的对象中,然后建立另一对象myArray,将对象内容赋值给myArray。类intArray重载了“=”运算符。程序中给出了一个测试数据文件input,不超过300个的整数。程序的输出是:
10
11
13
16
20
要求:
补充编制的内容写在“//**********333**********”与“//**********666**********”之间。实现重载赋值运算符函数,并将赋值结果在屏幕输出。格式不限。不得修改程序的其他部分。
注意:程序最后将结果输出到文件out.dat中。输出函数writeToFile已经编译为obj文件,并且在本程序中调用。
//intArray.h
class intArray

private:
int*array;
int length;
public:
intArray (char*filename);
intArray ();
intArray & operator=(const intArray & src);
~intArray ();
void show ();
;
void writeToFile (const char*path);
//main.cpp
#include<iostream>
#include<fstream>
#include<cstring>
#include "intArray.h"
using namespace std;
intArray::intArray ()

length=10;
array=new int[length];
intArray::intArray(char*filename)

ifstream myFile(filename);
array=new int[300];
length=0;
while (myFile>>array[length++])
length--;
myFile.close();

intArray& intArray::operator=(const intArray & src)

if (arrayl=NUll) delete [] array;
length=src.length;
array=new int[length];
return*this;
intArray::~intArray ()

delete [] array;

void intArray::show ()

int step =0;
for(int i=0;i<length;i=i+step)

cout<<array[i]<<endl;
step++;


void main ()

intArray*arrayP=new intArray("input.dat");
intArray myArray;
myArray=*arrayP;
(*arrayP).show();
delete arrayP;
writeToFile(" ");

答案

参考答案:for(int i=0;i<length;i++)
//遍历对象src中的数组array,然后依次把值放进数组array中
array[i]=src.array[i];

解析: 本题主要考查intArray类,其中涉及动态数组、构造函数、运算符重载、析构函数及其他成员函数。
主要考查考生对运算符重载的掌握,该函数要重载运算符“=”,该运算符的意思是赋值。先看该函数的其他语句:
if(array!=NULL)delete[]array;
length=src.length;
array=new int[lengthl;
第一条语句是把原来动态数组释放,第二条语句是把形参src的成员length赋值给变量length,第三条语句是给指针array分配内存。接下来要把动态数组中的值逐个赋给array数组,在这里使用for循环语句,循环变量i的范围是0~length,并进行赋值操作。

填空题
单项选择题