VC++习题参考答案

2026/4/23 20:00:45

{

CPoint point1; point1.display();

point1.setpoint(80,150); point1.display(); }

16.以下是一个类的测试程序,给出类的定义,构造一个完整的程序。执行程序时的输出如下。输出结果:200-60=140 主函数为: void main() {

CTest c;

c.init(200, 60); c.print(); }

CTest类的构造如下: #include class CTest {

int x,y; public:

void init(int x0,int y0) { x=x0; y=y0; } void print() {

cout<<\ } };

17.设有一个类,其定义如下: #include class CSample {

char *p1, *p2; public:

void init(char *s1, char *s2); void print()

{ cout<<\ void copy(CSample &one); void free(); };

成员函数init()是将s1和s2所指向的字符串分别送到p1和p2所指向的动态申请的

内存空间中,函数copy将对象one中的两个字符串复制到当前的对象中,free()函数释放p1和p2所指向的动态分配的内存空间。设计一个完整的程序,包括完成这3个函数的定义和测试工作。

#include #include class CSample {

char *p1, *p2; public:

void init(char *s1, char *s2); void print() {

cout<<\ }

void copy(CSample &one); void free(); };

void CSample::init(char *s1, char *s2) {

p1=new char[strlen(s1)+1]; p2=new char[strlen(s2)+1]; strcpy(p1,s1); strcpy(p2,s2); }

void CSample::copy(CSample &one) {

if (this!=&one ) *this=one; }

void CSample::free() {

delete[] this->p1; delete[] this->p2; }

void main() {

CSample a,b;

a.init(\

a.print(); b.copy(a); b.print(); a.free(); }

本程序的设计是有问题的,最好是把new分配内存写在构造函数中!如此无法进行b.free()!因为对象b没有用new分配内存,因此不可以用delete运算符。

18.设有一个类,其定义如下: #include class CArray

{ int nSizeOfInt; //整型数组的大小

int nNumOfInt; //整型数组中实际存放的元素个数 int nSizeOfFloat; //浮点数组的大小

int nNumOfFloat; //浮点数组中实际存放的元素个数 int *pInt; //指向整型数组,动态分配内存空间 float *pFloat; //指向浮点数组,动态分配内存空间 public:

CArray(int nIntSize=100, int nFloatSize=200); void put(int n); //将n加入到整型数组中 void put(float x); //将x加入到浮点数组中

int getInt(int index); //取整型数组中第index个元素,index从0开始 float getFloat(int index); //取浮点数组中第index个元素,index从0开始 ~CArray(); //析构函数,释放动态分配的内存空间

void print(); //分别输出整型数组和浮点数组中的所有元素

};构造完整的程序,包括类成员函数的定义和测试程序的设计。构造函数中的nIntSize 和nFloatSize分别表示整型数组和浮点数组的大小。

CArray::CArray(int nIntSize, int nFloatSize) {

nSizeOfInt=nIntSize;

pInt=new int[nSizeOfInt]; nSizeOfFloat=nFloatSize;

pFloat=new float[nSizeOfFloat]; nNumOfInt=0;nNumOfFloat=0; }

void CArray::put(int n) {

pInt[nNumOfInt++]=n; }

void CArray::put(float x)

{ pFloat[nNumOfFloat++]=x; }

int CArray::getInt(int index) {

if (index>=0 && index<=nNumOfInt) return pInt[index]; }

float CArray::getFloat(int index) {

if (index>=0 && index<=nNumOfFloat) return pFloat[index]; }

CArray::~CArray() {

delete [] pFloat; delete [] pInt; }

void CArray::print() {

for( int i=0;i

for( int j=0;j

void main() { int a=10; float x=10.5;

CArray MyArray(10,15); MyArray.put(a); MyArray.put(x); MyArray.put(a+1); MyArray.put(x+1); MyArray.put(a+2); MyArray.put(x+2); MyArray.print(); }


VC++习题参考答案.doc 将本文的Word文档下载到电脑
搜索更多关于: VC++习题参考答案 的文档
相关推荐
相关阅读
× 游客快捷下载通道(下载后可以自由复制和排版)

下载本文档需要支付 10

支付方式:

开通VIP包月会员 特价:29元/月

注:下载文档有可能“只有目录或者内容不全”等情况,请下载之前注意辨别,如果您已付费且无法下载或内容有问题,请联系我们协助你处理。
微信:xuecool-com QQ:370150219