📄 pex6_8.cpp
字号:
#include <iostream.h>
#include <string.h>
class String
{
private:
char str[256];
public:
// constructor
String(char s[] = "");
int Length(void) const; // string length
void CString(char s[]) const; // copy string to C++ array s
// *****Stream I/O *****
friend ostream& operator<< (ostream& ostr, const String& s);
// Read whitespace separated strings
friend istream& operator>> (istream& istr, String& s);
// ***** relational operators *****
int operator== (String& s) const; // String == String
// ***** string concatenation *****
String operator+ (String& s) const;
};
// constructor. copy C++ string s to data member str
String::String(char s[])
{
strcpy(str,s);
}
// return the length of the string
int String::Length(void) const
{
return strlen(str);
}
// copy the data member str to the C++ string s
void String::CString(char s[]) const
{
strcpy(s,str);
}
// stream output
ostream& operator<< (ostream& ostr, const String& s)
{
cout << s.str;
return ostr;
}
// input whitespace separated strings
istream& operator>> (istream& istr, String& s)
{
istr >> s.str;
return istr;
}
// test current object and s for equality
int String::operator== (String& s) const
{
return strcmp(str,s.str) == 0;
}
// return a String object that consists of s
// concatenated onto the current object
String String::operator+ (String& s) const
{
String temp;
// copy str to temp.str
strcpy(temp.str,str);
// concatenate s.str onto the end of temp.str
strcat(temp.str,s.str);
// return the new object
return temp;
}
// test the class by running the following program.
void main(void)
{
String S1("It is a "), S2("beautiful day!"), S3;
char s[30];
// note there is no blank after the 'a'. if the
// blank is present, the strings are equal
if (S1 == String("It is a"))
cout << "Equality test O.K." << endl;
else
cout << "Equality test failed." << endl;
cout << "The length of S1 = " << S1.Length() << endl;
cout << "Enter a string S3: ";
cin >> S3;
// note that it is a good idea to echo the input string
cout << S3 << endl;
S3 = S1 + S2;
cout << "The concatenation of S1 and S2 is '"
<< S3 << "'" << endl;
S3.CString(s);
cout << "The C++ string stored in S3 is '" << s << "'" << endl;
}
/*
<Run>
Equality test failed.
The length of S1 = 8
Enter a string S3: wonderful
wonderful
The concatenation of S1 and S2 is It is a beautiful day!
The C++ string stored in S3 is 'It is a beautiful day!'
*/
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -