【C++初学】课后作业汇总复习(七) 指针-深浅copy

[复制链接]
发表于 4 小时前 | 显示全部楼层 |阅读模式
1、 HugeInt类:构造、+、cout

Description:
32位整数的盘算机可以表现整数的范围近似为-20亿到+20亿。在这个范围内使用一样寻常不会出现标题,但是有的应用步调大概须要使用超出上述范围的整数。C++可以满足这个需求,创建功能强盛的新的数据范例。
界说一个HugeInt类,使用一个数组存储大整数的每一位。如 short integer[ 40 ]; 即可实现存储位数为40位的整数。暂不思量负数。请根据主函数为该类:
1)界说两个构造,分别继承int和string范例的参数;当参数为string范例时,可以使用字符串处理处罚函数将string范例转换为数值范例。
2)重载+运算,分别可以大概实现两个HugeInt对象相加,HugeInt与int相加,HugeInt与string相加。提示,先实现两个HugeInt相加,当HugeInt与int相加时,可以将int通过转换构造函数转换为HugeInt范例,然后调用两个HugeInt相加。HugeInt与string相加亦云云。
3)重载<<运算符。
注意:步调前缀、后缀代码已给出。
Sample Input:

Sample Output:
  1. //StudybarCommentBegin
  2. #include <iostream>
  3. #include <cctype> // isdigit function prototype
  4. #include <cstring> // strlen function prototype
  5. using namespace std;
  6. class HugeInt
  7. {
  8.     friend ostream &operator<<( ostream &, const HugeInt & );
  9. public:
  10.     static const int digits = 30;
  11.     HugeInt( long = 0 ); // conversion/default constructor
  12.     HugeInt( const char * ); // conversion constructor
  13.    
  14.     // addition operator; HugeInt + HugeInt
  15.     HugeInt operator+( const HugeInt & ) const;
  16.    
  17.     // addition operator; HugeInt + int
  18.     HugeInt operator+( int ) const;
  19.    
  20.     // addition operator;
  21.     // HugeInt + string that represents large integer value
  22.     HugeInt operator+( const char * ) const;
  23.    
  24.     int getLength() const;
  25. private:
  26.     short integer[ digits ];
  27. }; // end class HugeInt
  28. //StudybarCommentEnd
  29. // Implementation of HugeInt class
  30. HugeInt::HugeInt(long value) {
  31.     // Initialize all digits to 0
  32.     for (int i = 0; i < digits; i++) {
  33.         integer[i] = 0;
  34.     }
  35.    
  36.     // Store digits in reverse order
  37.     for (int i = digits - 1; value != 0 && i >= 0; i--) {
  38.         integer[i] = value % 10;
  39.         value /= 10;
  40.     }
  41. }
  42. HugeInt::HugeInt(const char *str) {
  43.     // Initialize all digits to 0
  44.     for (int i = 0; i < digits; i++) {
  45.         integer[i] = 0;
  46.     }
  47.    
  48.     int len = strlen(str);
  49.     int j = digits - 1;
  50.    
  51.     // Store digits in reverse order
  52.     for (int i = len - 1; i >= 0 && j >= 0; i--) {
  53.         if (isdigit(str[i])) {
  54.             integer[j--] = str[i] - '0';
  55.         }
  56.     }
  57. }
  58. HugeInt HugeInt::operator+(const HugeInt &op2) const {
  59.     HugeInt temp;
  60.     int carry = 0;
  61.    
  62.     for (int i = digits - 1; i >= 0; i--) {
  63.         temp.integer[i] = integer[i] + op2.integer[i] + carry;
  64.         
  65.         if (temp.integer[i] > 9) {
  66.             temp.integer[i] %= 10;
  67.             carry = 1;
  68.         } else {
  69.             carry = 0;
  70.         }
  71.     }
  72.    
  73.     return temp;
  74. }
  75. HugeInt HugeInt::operator+(int op2) const {
  76.     return *this + HugeInt(op2);
  77. }
  78. HugeInt HugeInt::operator+(const char *op2) const {
  79.     return *this + HugeInt(op2);
  80. }
  81. int HugeInt::getLength() const {
  82.     int i;
  83.     for (i = 0; (i < digits) && (integer[i] == 0); i++)
  84.         ; // skip leading zeros
  85.    
  86.     return (i == digits) ? 1 : (digits - i);
  87. }
  88. ostream &operator<<(ostream &output, const HugeInt &num) {
  89.     int i;
  90.     for (i = 0; (i < HugeInt::digits) && (num.integer[i] == 0); i++)
  91.         ; // skip leading zeros
  92.    
  93.     if (i == HugeInt::digits) {
  94.         output << 0;
  95.     } else {
  96.         for (; i < HugeInt::digits; i++) {
  97.             output << num.integer[i];
  98.         }
  99.     }
  100.    
  101.     return output;
  102. }
  103. //StudybarCommentBegin
  104. int main()
  105. {
  106.     HugeInt n1( 7654321 );
  107.     HugeInt n2( 7891234 );
  108.     HugeInt n3( "99999999999999999999999999999" );
  109.     HugeInt n4( "1" );
  110.     HugeInt result;
  111.    
  112.     cout << "n1 is " << n1 << "\nn2 is " << n2
  113.     << "\nn3 is " << n3 << "\nn4 is " << n4
  114.     << "\nresult is " << result << "\n\n";
  115.    
  116.    
  117.     result = n1 + n2;
  118.     cout << n1 << " + " << n2 << " = " << result << "\n\n";
  119.    
  120.     cout << n3 << " + " << n4 << "\n= " << ( n3 + n4 ) << "\n\n";
  121.    
  122.     result = n1 + 9;
  123.     cout << n1 << " + " << 9 << " = " << result << endl;
  124.    
  125.     result = n2 + "10000";
  126.     cout << n2 << " + " << "10000" << " = " << result << endl;
  127.     return 0;
  128. } // end main
  129. //StudybarCommentEnd
复制代码
2、对象指针界讨情势——代码改正

对象指针界讨情势
类名 *对象指针名;
例:
Point a(5,10);
Piont *ptr;
ptr=&a;
通过指针访问对象成员
对象指针名->成员名
例:ptr->getx() 相称于 (*ptr).getx();
例6-12使用指针来访问Point类的成员
//6_12.cpp
#include
using namespace std;
class Point {
public:
Point(int x = 0, int y = 0) : x(x), y(y) { }
int getX() const { return this->x; }
int getY() const { return  y; }
private:
int x, y;
};
int main() {
Point a(4, 5);
Point  p1 = &a; //界说对象指针,用a的所在初始化
cout << p1.getX() << endl;//用指针访问对象成员
cout << a->getY() << endl; //用对象名访问对象成员
return 0;
}
本题输出结果
4
5
  1. #include <iostream>
  2. using namespace std;
  3. class Point {
  4. public:
  5.     Point(int x = 0, int y = 0) : x(x), y(y) { }
  6.     int getX() const { return this->x; }
  7.     int getY() const { return y; }
  8. private:
  9.     int x, y;
  10. };
  11. int main() {
  12.     Point a(4, 5);
  13.     Point *p1 = &a; // 定义对象指针,用a的地址初始化
  14.     cout << p1->getX() << endl; // 用指针访问对象成员
  15.     cout << a.getY() << endl; // 用对象名访问对象成员
  16.     return 0;
  17. }
复制代码
3、动态创建对象举例

动态内存分配
动态申请内存使用符 new
new 范例名T(初始化参数列表)
功能:在步调实验期间,申请用于存放T范例对象的内存空间,并依初值列表赋以初值。
结果值:乐成:T范例的指针,指向新分配的内存;失败:抛出非常。
开释内存使用符delete
delete 指针p
功能:开释指针p所指向的内存。p必须是new使用的返回值。
本题给出了前缀,本题步调,应该和下列代码等价!
例6-16 动态创建对象举例
#include
using namespace std;
class Point {
public:
Point() : x(0), y(0) {
cout<<“Default Constructor called.”<<endl;
}
Point(int x, int y) : x(x), y(y) {
cout<< “Constructor called.”<<endl;
}
~Point() { cout<<“Destructor called.”<<endl; }
int getX() const { return x; }
int getY() const { return y; }
void move(int newX, int newY) {
x = newX;
y = newY;
}
private:
int x, y;
};
int main() {
cout << "Step one: " << endl;
Point *ptr1 = new Point; //调用默认构造函数
cout<getX()<<endl; //输出GetX
delete ptr1; //删除对象,主动调用析构函数
cout << "Step two: " << endl;
ptr1 = new Point(1,2);
cout<getX()<<endl; //输出GetX
delete ptr1;
return 0;
}
  1. //StudybarCommentBegin
  2. #include <iostream>
  3. using namespace std;
  4. class Point {
  5. public:
  6.         Point();
  7.         Point(int x, int y);
  8.         ~Point();
  9.         int getX() const;
  10.         int getY() const;
  11.         void move(int newX, int newY);
  12. private:
  13.         int x, y;
  14. };
  15. //StudybarCommentEnd
  16. Point::Point() : x(0), y(0) {
  17.     cout << "Default Constructor called." << endl;
  18. }
  19. Point::Point(int x, int y) : x(x), y(y) {
  20.     cout << "Constructor called." << endl;
  21. }
  22. Point::~Point() {
  23.     cout << "Destructor called." << endl;
  24. }
  25. int Point::getX() const {
  26.     return x;
  27. }
  28. int Point::getY() const {
  29.     return y;
  30. }
  31. void Point::move(int newX, int newY) {
  32.     x = newX;
  33.     y = newY;
  34. }
  35. int main() {
  36.     cout << "Step one: " << endl;
  37.     Point *ptr1 = new Point; //调用默认构造函数
  38.     cout << ptr1->getX() << endl; //输出GetX
  39.     delete ptr1; //删除对象,自动调用析构函数
  40.     cout << "Step two: " << endl;
  41.     ptr1 = new Point(1,2);
  42.     cout << ptr1->getX() << endl; //输出GetX
  43.     delete ptr1;
  44.     return 0;
  45. }
复制代码
4、 动态创建对象数组举例

例6-17 动态创建对象数组举例
分配和开释动态数组
分配:new 范例名T [ 数组长度 ]
数组长度可以是任何表达式,在运行时盘算
开释:delete[] 数组名p
开释指针p所指向的数组。
p必须是用new分配得到的数组首所在。
例6-17 动态创建对象数组举例
  1. #include<iostream>
  2. using namespace std;
  3. #include <iostream>
  4. using namespace std;
  5. class Point {
  6. public:
  7. Point() : x(0), y(0) {
  8. cout<<"Default Constructor called."<<endl;
  9. }
  10. Point(int x, int y) : x(x), y(y) {
  11. cout<< "Constructor called."<<endl;
  12. }
  13. ~Point() { cout<<"Destructor called."<<endl; }
  14. int getX() const { return x; }
  15. int getY() const { return y; }
  16. void move(int newX, int newY) {
  17. x = newX;
  18. y = newY;
  19. }
  20. private:
  21. int x, y;
  22. };
  23. int main() {
  24. Point *ptr = new Point[2]; //创建对象数组
  25. ptr[0].move(5, 10); //通过指针访问数组元素的成员
  26. cout<<ptr[0].getY()<<endl;
  27. ptr[1].move(15, 20); //通过指针访问数组元素的成员
  28. cout<<ptr[1].getY()<<endl;   
  29. cout << "Deleting..." << endl;
  30. delete[] ptr; //删除整个对象数组
  31. return 0;
  32. }
复制代码
5、浅层复制与深层复制

浅层复制
实现对象间数据元素的逐一对应复制。
深层复制
当被复制的对象数据成员是指针范例时,不是复制该指针成员自己,而是将指针所指对象举行复制
例6-21 对象的浅层复制
#include
#include
using namespace std;
class Point {
//类的声明同例6-16
//……
};
class ArrayOfPoints {
//类的声明同例6-18
//……
};
int main() {
int count;
cout << "lease enter the count of points: ";
cin >> count;
ArrayOfPoints pointsArray1(count); //创建对象数组
pointsArray1.element(0).move(5,10);
pointsArray1.element(1).move(15,20);
ArrayOfPoints pointsArray2(pointsArray1); //创建副本
cout << “Copy of pointsArray1:” << endl;
cout << "oint_0 of array2: " << pointsArray2.element(0).getX() << ", "
<< pointsArray2.element(0).getY() << endl;
cout << "oint_1 of array2: " << pointsArray2.element(1).getX() << ", "
<< pointsArray2.element(1).getY() << endl;
pointsArray1.element(0).move(25, 30);
pointsArray1.element(1).move(35, 40);
cout<<“After the moving of pointsArray1:”<<endl;
cout << "oint_0 of array2: " << pointsArray2.element(0).getX() << ", "
<< pointsArray2.element(0).getY() << endl;
cout << "oint_1 of array2: " << pointsArray2.element(1).getX() << ", "
<< pointsArray2.element(1).getY() << endl;
return 0;
}
运行结果如下:
Please enter the number of points:2
Default Constructor called.
Default Constructor called.
Copy of pointsArray1:
Point_0 of array2: 5, 10
Point_1 of array2: 15, 20
After the moving of pointsArray1:
Point_0 of array2: 25, 30
Point_1 of array2: 35, 40
Deleting…
Destructor called.
Destructor called.
Deleting…
接下来步调出现运行错误。

例6-22 对象的深层复制
#include
#include
using namespace std;
class Point { //类的声明同例6-16
};
class ArrayOfPoints {
public:
ArrayOfPoints(const ArrayOfPoints& pointsArray);
//其他成员同例6-18
};
ArrayOfPoints::ArrayOfPoints(const ArrayOfPoints& v) {
size = v.size;
points = new Point[size];
for (int i = 0; i < size; i++)
points = v.points;
}
int main() {
//同例6-20
}
步调的运行结果如下:
Please enter the number of points:2
Default Constructor called.
Default Constructor called.
Default Constructor called.
Default Constructor called.
Copy of pointsArray1:
Point_0 of array2: 5, 10
Point_1 of array2: 15, 20
After the moving of pointsArray1:
Point_0 of array2: 5, 10
Point_1 of array2: 15, 20
Deleting…
Destructor called.
Destructor called.
Deleting…
Destructor called.
Destructor called.
  1. #include <iostream>
  2. #include <cassert>
  3. using namespace std;
  4. class Point {
  5. public:
  6.     Point() : x(0), y(0) {
  7.         cout << "Default Constructor called." << endl;
  8.     }
  9.     ~Point() {
  10.         cout << "Destructor called." << endl;
  11.     }
  12.     void move(int newX, int newY) { x = newX; y = newY; }
  13.     int getX() const { return x; }
  14.     int getY() const { return y; }
  15. private:
  16.     int x, y;
  17. };
  18. class ArrayOfPoints {
  19. public:
  20.     ArrayOfPoints(int size) : size(size) {
  21.         points = new Point[size];
  22.     }
  23.    
  24.     // 复制构造函数(深层复制)
  25.     ArrayOfPoints(const ArrayOfPoints& v) {
  26.         size = v.size;
  27.         points = new Point[size];
  28.         for (int i = 0; i < size; i++)
  29.             points[i] = v.points[i];
  30.     }
  31.    
  32.     ~ArrayOfPoints() {
  33.         cout << "Deleting..." << endl;
  34.         delete[] points;
  35.     }
  36.    
  37.     Point& element(int index) {
  38.         assert(index >= 0 && index < size);
  39.         return points[index];
  40.     }
  41.    
  42. private:
  43.     Point* points;
  44.     int size;
  45. };
  46. int main() {
  47.     int count;
  48.     cout << "Please enter the number of points:" << endl;
  49.     cin >> count;
  50.    
  51.     ArrayOfPoints pointsArray1(count); //创建对象数组
  52.     pointsArray1.element(0).move(5, 10);
  53.     pointsArray1.element(1).move(15, 20);
  54.    
  55.     ArrayOfPoints pointsArray2(pointsArray1); //创建副本(深层复制)
  56.    
  57.     cout << "Copy of pointsArray1:" << endl;
  58.     cout << "Point_0 of array2: " << pointsArray2.element(0).getX() << ", "
  59.          << pointsArray2.element(0).getY() << endl;
  60.     cout << "Point_1 of array2: " << pointsArray2.element(1).getX() << ", "
  61.          << pointsArray2.element(1).getY() << endl;
  62.    
  63.     pointsArray1.element(0).move(25, 30);
  64.     pointsArray1.element(1).move(35, 40);
  65.    
  66.     cout << "After the moving of pointsArray1:" << endl;
  67.     cout << "Point_0 of array2: " << pointsArray2.element(0).getX() << ", "
  68.          << pointsArray2.element(0).getY() << endl;
  69.     cout << "Point_1 of array2: " << pointsArray2.element(1).getX() << ", "
  70.          << pointsArray2.element(1).getY() << endl;
  71.    
  72.     return 0;
  73. }
复制代码
6、动态数组——根本模板类

本标题有后缀
标题形貌:
动态数组,是相对于静态数组而言。静态数组的长度是编程时步调员预先界说好的,在整个步调运行中,数组巨细无法改变。
而动态数组则否则,它可以随步调运行的须要而在运行时重新指定巨细。
动态数组的内存空间是从堆(heap)上分配(即动态分配)的。是通过实验new(或malloc等函数)使用,而为其分配存储空间。当步调实验到这些语句时,才为其分配。
对于动态数组类所申请的内存,在使用完必须由步调员自己开释,否则严峻会引起内存走漏。
以是内存的申请肯定要有借有还,才气再借不难,也要注意,不能多还。
已知动态数组模板类的界说如下。
请增补完备
1、构造函数
2、析构函数
3、返回空间巨细的 capacity()  函数
4、operator[] 重载
template
class DynamicArray {
private:
T* array; //pointer  ,一个T范例的指针
unsigned int mallocSize; //分配空间的巨细。
public:
//Constructors
// cout<<endl<< “new T[”<mallocSize<<“] malloc “<< this->mallocSize << “*”<<sizeof(T)<<”=”<mallocSize *sizeof(T)<<" bytes memory in heap";
DynamicArray(unsigned length, const T &content) ; // mallocSize=length; 设置每个元素的初始内容是 content;
// Destructors
// cout<<endl<< “delete[] array free “<< this->mallocSize << “*”<<sizeof(T)<<”=”<mallocSize *sizeof(T)<<" bytes memory in heap";
~DynamicArray();
//return the this->mallocSize
unsigned int capacity() const;
// for the array=someT.
T& operator[](unsigned int i) ;
};
输入一个整数
输出请分析拜见下面的用例和步调后缀。
样例输入:
3
样例输出
new T[3] malloc 34=12 bytes memory in heap
new T[3] malloc 3
8=24 bytes memory in heap
capacity:3
-1 -1 -1
-2.1 -2.1 -2.1
0 1 2
0 1.1 2.2
delete[] array free 38=24 bytes memory in heap
delete[] array free 3
4=12 bytes memory in heap
  1. #include <iostream>
  2. using namespace std;
  3. template <typename T>
  4. class DynamicArray {
  5. private:
  6.     T* array; //pointer  ,一个T类型的指针
  7.     unsigned int mallocSize; //分配空间的大小。
  8. public:
  9.     //Constructors
  10.     // cout<<endl<< "new T["<<this->mallocSize<<"] malloc "<< this->mallocSize << "*"<<sizeof(T)<<"="<<this->mallocSize *sizeof(T)<<" bytes memory in heap";
  11.     DynamicArray(unsigned length, const T &content) {
  12.         mallocSize = length;
  13.         array = new T[length];
  14.         for (unsigned int i = 0; i < length; ++i) {
  15.             array[i] = content;
  16.         }
  17.         cout << "new T[" << mallocSize << "] malloc " << mallocSize << "*" << sizeof(T) << "=" << mallocSize * sizeof(T) << " bytes memory in heap\n";
  18.     }
  19.     // Destructors
  20.     // cout<<endl<< "delete[] array free "<< this->mallocSize << "*"<<sizeof(T)<<"="<<this->mallocSize *sizeof(T)<<" bytes memory in heap";
  21.     ~DynamicArray() {
  22.         cout << endl << "delete[] array free " << mallocSize << "*" << sizeof(T) << "=" << mallocSize * sizeof(T) << " bytes memory in heap";
  23.         delete[] array;
  24.     }
  25.     //return the this->mallocSize
  26.     unsigned int capacity() const {
  27.         return mallocSize;
  28.     }
  29.     // for the array[i]=someT.
  30.     T& operator[](unsigned int i) {
  31.         return array[i];
  32.     }
  33. };
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
继续阅读请点击广告

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
回复

使用道具 举报

×
登录参与点评抽奖,加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表