7.3.
,
String.
Stirng?
Stirng: ? ?
? ,
, , ,
.
:
String inBuf;
while (
readString( cin, inBuf ))
{ if ( inBuf.isEmpty() ) return;
if (
inBuf.isEqul( "done" )) return;
switch( inBuf.index(0) ) { /* ... */
}
cout << "String is ";
writeString( cout, inBuf );
}
. , String,
, . ,
, ,
String:
String inBuf;
while ( cin
>> inBuf )
{ if ( !inBuf ) return;
if ( inBuf == "done" )
return;
switch( inBuf[ 0 ] ) { /* ... */ }
cout << "String is "
<< inBuf; }
,
String.
.
,
.
.
, , ,
operator,
++ . ,
String&
String::Operator=( const String& s )
{ // assign one String object to
another
len = s.len;
delete str; // deallocate existing array
str = new
char[ len + 1 ];
strcpy( str, s.str );
return *this; }
String
String.
#include "String.h"
String article( "the"
);
String common;
main()
{ // String::Operator=()
common = article;
}
, . ,
String String
char*.
class String
{
public:
String &operator=(
const String& );
String &operator=( const char* );
//
...
};
strcmp()
. String,
String :
String::Operator==( String& st
)
{ // strcmp return 0 if both strings are equal
// operator== returns 1
for equality
return( strmcp( str, st.str ) == 0
);}
++ .
(**, , ).
7.1 , .
-
+ - * / % ^ & | ~ !
=
< > <= >= ++ -- << >> == != &&
|| += -= /= %=
^= &= |= <<= >>= []
() -> ->* new
delete
. ,
,
.
. , ,
.
. ,
.
( 3.9 ) .
,
x == y + z;
operator+ operator==.
.
. NOT (!), ,
String.
:
// illegal: ! is a unary
operator
operator!( String st1, String st2 )
{ return( strcmp(st1.str,
st2.str ) != 0 ); }
(+, -,
* &) , .
.
(++, ).
.
,
. ,
String,
String st1( "cobble" );
String st2( "stone"
);
String st3 = st1 + st2;
Stirng:
class String { friend String&
operator+( String&, String& );
// ... };
:
class String { public: String& operator+( String&
);
// ... };
:
class String
{ friend String& operator+(
String&, String& );
public: String& operator+( String&
);
// ... };
String a( "hobby" ), b( "horse" );
String c = a + b;
// error: anbiguous
- . ,
,
. ,
st1 + st2
:
st1.operator+( st2 )
:
operator+( st1, st2 )
,
.
,
: (=),
([]), (())
(->).
.
. ,
.
, .
,
class String {
friend ostream& operator<<(
ostream& os, String& s )
{ return ( os << s.str ); }
// ...
};
7-11.
operator+() -
String.
7-12. NOT 1
String ; 0.
String.
7-13. operator+()
String. .
7-14.
operator+()
String.
[]
String
str.
String:
String sentence( "Ash on an old mans sleeve." );
String
tempBuf( sentence.getLen() );
for ( int i = 0; i < sentence.getLen(); ++i
)
tempBuf[ i ] = sentence[ i ];
String::getLen()
, String:
inline String::getLen() {
return len; }
, .
.
:
inline char& String::Operator[](
int elem )
{ checkBounds( elem );
return str[ elem ]; }
.
.
,
String st( "mauve" );
st[0] = M;
st.str.
checkBounds()
String. .
:
// pull in exit(int) prototype
#include
<stdlib.h>
void String::checkBounds( int elem )
{ // check array
bounds
if ( elem < 0 || elem >= len )
{ cerr << "nString
Array Out of Bounds! index: " << elem << " string length (0-"
<< len-1 << ")n";
exit( -1 ); } }