云题海 - 专业文章范例文档资料分享平台

当前位置:首页 > 2.1 类和对象(第二章 C++面向对象程序设计)

2.1 类和对象(第二章 C++面向对象程序设计)

  • 62 次阅读
  • 3 次下载
  • 2025/5/1 11:38:49

a.display();

cout << \ a.setpoint(); a.display(); }

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

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

完整程序:

#include using namespace std;

class CTest { public:

CTest():x(0), y(0) { }

void init(int i, int j) {

x = i; y = j; }

void print() {

cout << x << \ }

private: int x; int y; };

void main() {

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

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

char *p1,*p2; public:

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

{cout<<”p1=”<

}

成员函数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::free() { delete [] p1; delete [] p2; }

void CSample::copy(CSample & one) {

delete [] p1; delete [] p2;

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

int main() {

CSample c,one; CSample & One=one; char s1[]=\ char s2[]=\

char s3[]=\ char s4[]=\ c.init(s1,s2); one.init(s3,s4); cout<<\打印 c:\ c.print();

cout<<\打印one:\ one.print(); c.copy(One);

cout<<\打印 c:\ c.print(); c.free(); one.free(); return 0; }

18、设有一个类,其定义如下: class CArray {

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

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

int nNumOfFlaot; //浮点数组中实际存放的元素个数 int *pInt; //指向整型数组,动态分配内存空间 int *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(); //分别输出整型数组和浮点数组中的所有元素 }

  • 收藏
  • 违规举报
  • 版权认领
下载文档10.00 元 加入VIP免费下载
推荐下载
本文作者:...

共分享92篇相关文档

文档简介:

a.display(); cout << \ a.setpoint(); a.display(); } 16、以下是一个类的测试程序,给出类的定义,构造一个完整的程序。执行程序的输出如下。 输出结果:200-60=140 主函数为: void main() { CTest c; c.init(200,60); c.print(); } 完整程序: #include using namespace std; class CTest { public: CTest():x(0), y(0) { }

× 游客快捷下载通道(下载后可以自由复制和排版)
单篇付费下载
限时特价:10 元/份 原价:20元
VIP包月下载
特价:29 元/月 原价:99元
低至 0.3 元/份 每月下载150
全站内容免费自由复制
VIP包月下载
特价:29 元/月 原价:99元
低至 0.3 元/份 每月下载150
全站内容免费自由复制
注:下载文档有可能“只有目录或者内容不全”等情况,请下载之前注意辨别,如果您已付费且无法下载或内容有问题,请联系我们协助你处理。
微信:fanwen365 QQ:370150219
Copyright © 云题海 All Rights Reserved. 苏ICP备16052595号-3 网站地图 客服QQ:370150219 邮箱:370150219@qq.com