C++实验2报告-面向对象程序设计.docx
C+实验2报告-面向对象程序设计 Lab Exercises Class: Name: StuID: Date: 2022-12-5 Score: Lab Exercise 1 String Concatenation I Lab Objectives In this lab, you will practice: 1) Overloading the + operator to allow String objects to be concatenated. 2) Writing function prototypes for overloaded operators. 3) Using overloaded operators. II Description of the Problem String concatenation(连接)requires two operandsthe two strings that are to be concatenated. In the text, we showed how to implement an overloaded concatenation operator that concatenates the second String object to the right of the first String object, thus modifying the first String object. In some applications, it is desirable to produce a concatenated String object without modifying the String arguments. Implement operator+ to allow operations such as string1 = string2 + string3; in which neither operand is modified. III Sample Output IV Problem-Solving Tips 1. The overloaded + operator should be a member function of class String and should take one parameter, a const reference to a String. 2. The + operator function should use return type String. 3. The strcat function can be used to concatenate pointer-based strings. V Your Solution #define _CRT_SECURE_NO_DEPRECATE #include #include #include "String.h" using namespace std; String:String(const char * const zPtr) length = strlen(zPtr); sPtr = new charlength + 1; assert(sPtr != 0); strcpy(sPtr, zPtr); String:String(const String ©) length = copy.length; sPtr = new charlength + 1; assert(sPtr != 0); strcpy(sPtr, copy.sPtr); String:String() delete sPtr; const String &String:operator=(const String &right) if (&right != this) delete sPtr; length = right.length; sPtr = new charlength + 1; assert(sPtr != 0); strcpy(sPtr, right.sPtr); else cout , >= and = 0; j-) integerj = value % 10; value /= 10; HugeInt:HugeInt(const char *string) for (int i = 0; i = 0; i-) temp.integeri = integeri + op2.integeri + carry; if (temp.integeri > 9) temp.integeri %= 10; carry = 1; else carry = 0; return temp; HugeInt HugeInt:operator-(const HugeInt &op2) const HugeInt temp; int carry = 0; for (int i = 29; i >= 0; i-) temp.integeri = integeri - op2.integeri; for (int i = 29; i >= 0; i-) if (temp.integeri op2.integeri) return false; return false; bool HugeInt:operator(HugeInt &op2) if (*this =(HugeInt &op2) if (*this > op2) return true; if (*this = op2) return true; return false; ostream& operator(HugeInt &); bool operator>=(HugeInt &); int getLength() const; int i; private: short integer30; ; #endif #include #include "Hugeint.h" using namespace std; int main() HugeInt n1(7654321); HugeInt n2(7891234); HugeInt n3("99999999999999999999999999999"); HugeInt n4("1"); HugeInt result; cout n2) cout = n2) cout and != operators can be implemented in terms of = and (const RationalNumber &right) const