Code:
124: // creates a new string by adding current
125: // string to rhs
126: String String::operator+(const String& rhs)
127: {
128: int totalLen = itsLen + rhs.GetLen();
129: String temp(totalLen);
130: int i, j;
131: for (i = 0; i<itsLen; i++)
132: temp[i] = itsString[i];
133: for (j = 0; j<rhs.GetLen(); j++, i++)
134: temp[i] = rhs[j];
135: temp[totalLen]='\0';
136: return temp;
137: }
124: // creates a new string by adding current
125: // string to rhs
126: String String::operator+(const String& rhs)
127: {
128: int totalLen = itsLen + rhs.GetLen();
129: String temp(totalLen);
130: int i, j;
131: for (i = 0; i<itsLen; i++)
132: temp[i] = itsString[i];
133: for (j = 0; j<rhs.GetLen(); j++, i++)
134: temp[i] = rhs[j];
135: temp[totalLen]='\0';
136: return temp;
137: }
Citat:
Because operator+ is not (and can't be) a const function (it changes the object it is called on), attempting to write the following will cause a compile-time error:
String buffer = Edie.GetFirstName() + Edie.GetLastName();
GetFirstName() returns a constant String, and you can't call operator+ on a constant object.
String buffer = Edie.GetFirstName() + Edie.GetLastName();
GetFirstName() returns a constant String, and you can't call operator+ on a constant object.
Code:
1: class Employee
11: const String & GetFirstName() const
12: { return itsFirstName; }
24: private:
25: String itsFirstName;
1: class Employee
11: const String & GetFirstName() const
12: { return itsFirstName; }
24: private:
25: String itsFirstName;
Zasto ne mozemo da pozovemo operator + , sa konstantnim objektom ?
Kako to ovaj operator menja objekat za koji je pozvan, kada od dva niza (kakva god) pravi NOVI ?
Ovo je razumljivo u slucaju operatora += , koji stvarno menja niz iz kojeg je pozvan, pa je njegov return , modifikovan TAJ niz :
Code:
139: // changes current string, returns nothing
140: void String::operator+=(const String& rhs)
141: {
142: unsigned short rhsLen = rhs.GetLen();
143: unsigned short totalLen = itsLen + rhsLen;
144: String temp(totalLen);
145: for (int i = 0; i<itsLen; i++)
146: temp[i] = itsString[i];
147: for (int j = 0; j<rhs.GetLen(); j++, i++)
148: temp[i] = rhs[i-itsLen];
149: temp[totalLen]='\0';
150: *this = temp;
151: }
139: // changes current string, returns nothing
140: void String::operator+=(const String& rhs)
141: {
142: unsigned short rhsLen = rhs.GetLen();
143: unsigned short totalLen = itsLen + rhsLen;
144: String temp(totalLen);
145: for (int i = 0; i<itsLen; i++)
146: temp[i] = itsString[i];
147: for (int j = 0; j<rhs.GetLen(); j++, i++)
148: temp[i] = rhs[i-itsLen];
149: temp[totalLen]='\0';
150: *this = temp;
151: }
Ali, kod operatora + , cini se da stvari stoje malo drugacije.
Txx